Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generating all dates within a given range in python

I have two string variables which contain dates in yyyy-mm-dd format as follows :

date1 = '2011-05-03' date2 = '2011-05-10' 

I want to write code that generates all dates in the range date1 to date2. How can this be done in Python?

like image 638
Joe Avatar asked May 03 '11 10:05

Joe


People also ask

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.


1 Answers

Pandas is great for time series in general, and has direct support both for date ranges and date parsing (it's automagic).

import pandas as pd date1 = '2011-05-03' date2 = '2011-05-10' mydates = pd.date_range(date1, date2).tolist() 

It also has lots of options to make life easier. For example if you only wanted weekdays, you would just swap in bdate_range.

See https://pandas.pydata.org/pandas-docs/stable/user_guide/timeseries.html#generating-ranges-of-timestamps

like image 173
fantabolous Avatar answered Sep 28 '22 14:09

fantabolous