-1

I have a string in python which is

date="200601"

which represents in 2006 January

How do I get the list of dates in that particular month in the 'yyyy-mm-dd' format

and also how do I iterate over 200601 to 201903 ie. getting the all values between the two month wise.

example 200601,200602,200603...

Thanks and much appreciated.

1 Answers1

1

To get all the dates in the month of that year in the format of yyyy-mm-dd:

date = "200601"

import datetime, calendar
num_days = calendar.monthrange(int(date[:-2]), int(date[4:]))[1]
print([datetime.date(int(date[:-2]), int(date[4:]), day).strftime("%Y-%m-%d") for day in range(1, num_days+1)])

OUTPUT:

['2006-01-01', '2006-01-02', '2006-01-03', '2006-01-04', '2006-01-05', '2006-01-06', '2006-01-07', '2006-01-08', '2006-01-09', '2006-01-10', '2006-01-11', '2006-01-12', '2006-01-13', '2006-01-14', '2006-01-15', '2006-01-16', '2006-01-17', '2006-01-18', '2006-01-19', '2006-01-20', '2006-01-21', '2006-01-22', '2006-01-23', '2006-01-24', '2006-01-25', '2006-01-26', '2006-01-27', '2006-01-28', '2006-01-29', '2006-01-30', '2006-01-31']

And for the second question:

Print all day-dates between two dates

EDIT:

Continuing from the comments under this answer:

print([datetime.date(int(date[:-2]), int(date[4:]), day).strftime("%Y%d") for day in range(1, num_days+1)])

OUTPUT:

['200601', '200602', '200603', '200604', '200605', '200606', '200607', '200608', '200609', '200610', '200611', '200612', '200613', '200614', '200615', '200616', '200617', '200618', '200619', '200620', '200621', '200622', '200623', '200624', '200625', '200626', '200627', '200628', '200629', '200630', '200631']
DirtyBit
  • 16,613
  • 4
  • 34
  • 55
  • Thank you but can you tell me how do i get it in the following format [200601,200602,200603.....] . Iteration over months – Abeer Sheikh Mar 22 '19 at 13:11
  • @AbeerSheikh sure just replace `strftime("%Y-%m-%d")` with `strftime("%Y%d")` – DirtyBit Mar 22 '19 at 13:13
  • @AbeerSheikh if the answer helped you may accept it: https://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work cheers – DirtyBit Mar 25 '19 at 05:06