Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python - Get all dates within an interval

Tags:

python

date

Given two dates, for example:

December 1, 2017
June 1, 2018

I want to get this result:

January 1, 2018
February 1, 2018
March 1, 2018
April 1, 2018
May 1, 2018
June 1, 2018

Moreover, I also want to modify the intervals. In the case above, the interval is monthly. I also want it to become quarterly and semi-annually.

So, given December 1, 2017 and June 1, 2018, it will generate March 1, 2018 for semi-annual and so on...

I also want it inclusive which means that the end date should also be included

Is there a python package or function for this?

like image 638
JM Lontoc Avatar asked Oct 18 '25 18:10

JM Lontoc


2 Answers

Pendulum — and specifically its 'range' function — is good for this.

It will give you both the monthly interval dates and what I take you to mean three-month interval dates.

>>> import pendulum
>>> start = pendulum.Pendulum(2017, 12, 1)
>>> end = pendulum.Pendulum(2018, 6, 1)
>>> period = pendulum.period(start, end)
>>> [dt.format('%Y-%m-%d') for dt in  period.range('months')]
['2017-12-01', '2018-01-01', '2018-02-01', '2018-03-01', '2018-04-01', '2018-05-01', '2018-06-01']
>>> [dt.format('%Y-%m-%d') for dt in  period.range('months', 3)]
['2017-12-01', '2018-03-01', '2018-06-01']
like image 52
Bill Bell Avatar answered Oct 20 '25 07:10

Bill Bell


Pandas has a pretty good datetime library of functions.

import pandas as pd

start = pd.to_datetime('December 1, 2017')
end = pd.to_datetime('June 1, 2018')

Get first day of every month:

pd.date_range(start, end, freq='MS').strftime('%B %d, %Y').tolist()

['December 01, 2017',
 'January 01, 2018',
 'February 01, 2018',
 'March 01, 2018',
 'April 01, 2018',
 'May 01, 2018',
 'June 01, 2018']

Where you can use this chart for freq values.

pd.date_range(start, end, freq='QS').strftime('%B %d, %Y').tolist()

['January 01, 2018', 'April 01, 2018']
like image 38
Scott Boston Avatar answered Oct 20 '25 08:10

Scott Boston



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!