Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get all dates (month, day and year) between two dates in python?

Situation: I am trying to construct a simple method that accepts two different integers that represent two different dates. 20120525 for May 25, 2012 and 20120627 for June 26, 2012 as an example. I want this method to return a list of these integer types that represent all days between the two date parameters.

Question: Could I get any suggestions on how to do this and how to handle months of either 28, 29, 30 or 31 days in each. I think I can do this by extracting the numbers as integers through division/modding of powers of 10, and then incrementing these numbers as such with the particular conditions above, but I feel like there must be an easier way to do this.

like image 430
jab Avatar asked Jul 03 '12 18:07

jab


People also ask

How do I print the months between two dates in Python?

date(2020, 1, 1) today = datetime. date. today() for month in months_between(start_of_2020, today): print(month. strftime("%B %Y")) # January 2020, February 2020, March 2020, …

How do I iterate over a date range in Python?

We can use the date_range() function method that is available in pandas. It is used to return a fixed frequency DatetimeIndex. We can iterate to get the date using date() function.


2 Answers

You don't have to reinvent the wheel. Just parse the strings into datetime objects and let python do the math for you:

from dateutil import rrule
from datetime import datetime

a = '20120525'
b = '20120627'

for dt in rrule.rrule(rrule.DAILY,
                      dtstart=datetime.strptime(a, '%Y%m%d'),
                      until=datetime.strptime(b, '%Y%m%d')):
    print dt.strftime('%Y%m%d')

prints

20120525
20120526
20120527
…
20120625
20120626
20120627
like image 107
eumiro Avatar answered Oct 11 '22 01:10

eumiro


You can use pandas.date_range,

import pandas

pd.date_range('2012-05-25', '2012-06-27', freq='D')

which would produce,

DatetimeIndex(['2012-05-25', '2012-05-26', '2012-05-27', '2012-05-28',
               '2012-05-29', '2012-05-30', '2012-05-31', '2012-06-01',
               ...
               '2012-06-22', '2012-06-23', '2012-06-24', '2012-06-25',
               '2012-06-26', '2012-06-27'],
               dtype='datetime64[ns]', freq='D')
like image 22
rth Avatar answered Oct 11 '22 00:10

rth