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
The DateTime value is then converted to a date value using the dt. date() function.
To convert a datetime to a date, you can use the CONVERT() , TRY_CONVERT() , or CAST() function.
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With