Ad

Loop Through A List Of Date Strings: Strptime Outputs "Datetime.date(2011-7-5)" Instead Of (2011-7-5)

- 1 answer

I have the following problem:

I have a list of date strings:

dates = ['11-07-05',
         '11-07-01',
         '11-07-03',
         '11-07-04', etc]

I want to convert them into date formats and i have used the following code:

from datetime import datetime as dt
dateFormat = [dt.strptime(item[1],"%y-%m-%d").date() for item in dates

this should output a new list in the following format:

dateFormat = [2011-7-5,
              2011-7-1,
              2011-7-3,
              2011-7-4]

but the output turns out to be:

dateFormat = [datetime.date(2011-7-5),
              datetime.date(2011-7-1),
              datetime.date(2011-7-3),
              datetime.date(2011-7-4)]

My question is: How can i format the date strings into date format without the "datetime.date"?

Ad

Answer

You want to convert the string to datetime using datetime.strptime and then convert the datetime back to string using datetime.strftime

from datetime import datetime as dt

dates = ['11-07-05', '11-07-01', '11-07-03', '11-07-04']

# Iterate through the dates
# Convert string to datetime using strptime 
# and then convert the datetime back to string using strftime
dateFormat = [dt.strptime(item,"%y-%m-%d").date().strftime('%Y-%m-%d') for item in dates]

print(dateFormat)

The output will be

['2011-07-05', '2011-07-01', '2011-07-03', '2011-07-04']
Ad
source: stackoverflow.com
Ad