Home > Enterprise >  Creating a list of dates in specific format
Creating a list of dates in specific format

Time:06-09

I need to construct a list of dates in a specific format - Month Date,Year.

I've created the list of dates, but when I try to format them, I get a long list of two dates, 'May 05,2022' and 'June 06,2022' as shown here:

['May 05,2022', 'May 05,2022', 'May 05,2022', 'May 05,2022', 'May 05,2022', 'May 05,2022', 'May 05,2022', 'May 05,2022', 'May 05,2022', 'May 05,2022', 'May 05,2022', 'May 05,2022', 'May 05,2022', 'May 05,2022', 'May 05,2022', 'May 05,2022', 'May 05,2022', 'June 06,2022', 'June 06,2022', 'June 06,2022', 'June 06,2022', 'June 06,2022', 'June 06,2022', 'June 06,2022', 'June 06,2022']

I'm not sure what's going on, becasue when I print dates i get a list of all the dates in that range. Any strategy I use to format the numbers results in a bad list (above).

from datetime import datetime
import pandas as pd

START_REPORTING = datetime(2022, 5, 15)
TODAY = datetime.today()


dates = pd.date_range(start=START_REPORTING ,end=TODAY)

list = []
for i in dates:
    list.append(i.strftime('%B %m,%Y'))
print(list)
print(dates)



['May 05,2022', 'May 05,2022', 'May 05,2022', 'May 05,2022', 'May 05,2022', 'May 05,2022', 'May 05,2022', 'May 05,2022', 'May 05,2022', 'May 05,2022', 'May 05,2022', 'May 05,2022', 'May 05,2022', 'May 05,2022', 'May 05,2022', 'May 05,2022', 'May 05,2022', 'June 06,2022', 'June 06,2022', 'June 06,2022', 'June 06,2022', 'June 06,2022', 'June 06,2022', 'June 06,2022', 'June 06,2022']
DatetimeIndex(['2022-05-15', '2022-05-16', '2022-05-17', '2022-05-18',
               '2022-05-19', '2022-05-20', '2022-05-21', '2022-05-22',
               '2022-05-23', '2022-05-24', '2022-05-25', '2022-05-26',
               '2022-05-27', '2022-05-28', '2022-05-29', '2022-05-30',
               '2022-05-31', '2022-06-01', '2022-06-02', '2022-06-03',
               '2022-06-04', '2022-06-05', '2022-06-06', '2022-06-07',
               '2022-06-08'],
              dtype='datetime64[ns]', freq='D')


CodePudding user response:

You probably want to use the format string '%B %d, %Y', because %m gives you the month with a leading zero.

This should do what you want:

dates.to_series().dt.strftime('%B %d, %Y').to_list()

# ['May 15, 2022', 'May 16, 2022', 'May 17, 2022', 'May 18, 2022', 'May 19, 2022', 'May 20, 2022', 'May 21, 2022', 'May 22, 2022', 'May 23, 2022', 'May 24, 2022', 'May 25, 2022', 'May 26, 2022', 'May 27, 2022', 'May 28, 2022', 'May 29, 2022', 'May 30, 2022', 'May 31, 2022', 'June 01, 2022', 'June 02, 2022', 'June 03, 2022', 'June 04, 2022', 'June 05, 2022', 'June 06, 2022', 'June 07, 2022', 'June 08, 2022']

CodePudding user response:

Your date format translates to month_name month_number, year. Replacing %m with %d should work. Try this

for i in dates:
    list.append(i.strftime('%B %m,%Y'))
  • Related