Skip to content Skip to sidebar Skip to footer

Convert Datetime List Into Date Python

I have a datetime list and would like to convert it into a date using the following code: dates = (datetime.strptime(ts, '%Y-%m-%d %H:%M:%S') for ts in timestamps) date_strings = [

Solution 1:

It appears the values in your timestamps sequence are not strings; they are already datetime objects. You don't need to parse these any further. It is also possible you have a mix of strings and datetime objects; the exception you see is thrown because at least one of the values in timestamps is a datetime instance already.

Just call the datetime.strftime()method on all objects in ts to format them:

date_strings = [d.strftime('%m-%d-%Y') for d in timestamps]

Demo:

>>> import datetime
>>> timestamps = [datetime.datetime(2016, 11, 21, 0, 0), datetime.datetime(2016, 11, 22, 0, 0), datetime.datetime(2016, 11, 23, 0, 0)]
>>> [d.strftime('%m-%d-%Y') for d in timestamps]
['11-21-2016', '11-22-2016', '11-23-2016']

In the event that you have a mix of strings and datetime instances in timestamps, you'll have to do some extra processing:

defconvert_as_needed(ts):
    try:
        # parse strings
        datetime.strptime(ts, '%Y-%m-%d %H:%M:%S')
    except TypeError:
        # assume it is already a datetime objectreturn ts

dates = map(convert_as_needed, timestamps)
date_strings = [d.strftime('%m-%d-%Y') for d in dates]

Post a Comment for "Convert Datetime List Into Date Python"