6

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

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
MCM
  • 1,479
  • 2
  • 17
  • 22
  • `timestamps` is already a list of `datetime` objects; or more precisely, *at least one object in that list* is a `datetime` object. You can't use `datetime.strptime()` (note the *`p`* in there) to parse them to `datetime` objects *again*. – Martijn Pieters Dec 29 '16 at 21:40
  • Your `for d in dates` list comprehension needlessly uses an unbound `datetime.strftime()` method; just call the method directly on the `datetime` instances. – Martijn Pieters Dec 29 '16 at 21:41

1 Answers1

15

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]
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • one more question. After the conversion how can I add a day to the date? Using datetime.timedelta(1) does not work because it is a string now. Is there a easy workaroung? – MCM Dec 30 '16 at 08:54
  • Add your timedelta *before* converting to a string. `(d + timedelta(days=1)).strftime('%m-%d-%Y')` would let you do both in one expression. – Martijn Pieters Dec 30 '16 at 09:52
  • Thanks a lot that is what I was looking for – MCM Dec 30 '16 at 10:32