Issue
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
Solution
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]
Answered By - Martijn Pieters
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.