Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 = [datetime.strftime(d, '%m-%d-%Y') for d in dates]

The datetime list looks like the following:

[datetime.datetime(2016, 11, 21, 0, 0), datetime.datetime(2016, 11, 22, 0, 0), datetime.datetime(2016, 11, 23, 0, 0)]

I receive the following error message:

TypeError: strptime() argument 1 must be str, not datetime.datetime

like image 215
MCM Avatar asked Dec 29 '16 21:12

MCM


People also ask

How do I convert datetime to date in python?

The DateTime value is then converted to a date value using the dt. date() function.

How do I convert datetime to date?

To convert a datetime to a date, you can use the CONVERT() , TRY_CONVERT() , or CAST() function.


1 Answers

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:

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

dates = map(convert_as_needed, timestamps)
date_strings = [d.strftime('%m-%d-%Y') for d in dates]
like image 154
Martijn Pieters Avatar answered Sep 27 '22 19:09

Martijn Pieters