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.
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, …
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.
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
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')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With