Why datetime.datetime.strptime raises ValueError although the format is valid?

Viewed 641

I get this date string format from the database and I need to convert it to datetime object in order to do subtraction.

'from': '2020-06-24T10:12:00.692+00:00'

I've tried this formatting, but that does not work.

"%Y-%m-%dT%H:%M:%S.%f%z"

Is that string even convertible in python?

Update: That's the strptime I run

datetime_obj1= datetime.strptime(row['from'], "%Y-%m-%dT%H:%M:%S.%f%z")

The error I get

ValueError                                Traceback (most recent call last)
<ipython-input-11-7798f7219c52> in <module>
     23 for row in list_of_events:
     24     print(row['id'])
---> 25     datetime_obj1= datetime.strptime(row['from'], "%Y-%m-%dT%H:%M:%S%z")
     26     print(datetime_obj1)
     27     #print(row['from']-row['to'])

/usr/lib/python3.6/_strptime.py in _strptime_datetime(cls, data_string, format)
    563     """Return a class cls instance based on the input string and the
    564     format string."""
--> 565     tt, fraction = _strptime(data_string, format)
    566     tzname, gmtoff = tt[-2:]
    567     args = tt[:6] + (fraction,)

/usr/lib/python3.6/_strptime.py in _strptime(data_string, format)
    360     if not found:
    361         raise ValueError("time data %r does not match format %r" %
--> 362                          (data_string, format))
    363     if len(data_string) != found.end():
    364         raise ValueError("unconverted data remains: %s" %

ValueError: time data '2020-06-24T10:12:00.692+00:00' does not match format '%Y-%m-%dT%H:%M:%S%z'
3 Answers

There is an issue about parsing RFC 3339 dates and times at here and it is resolved on python3.7.

So %z is not supported for < .

Without some actual code it's hard to say, where your mistake was.

The date format you suggested works just fine...

>>> from datetime import datetime
>>> datetime.strptime("2020-06-24T10:12:00.692+00:00", "%Y-%m-%dT%H:%M:%S.%f%z")
datetime.datetime(2020, 6, 24, 10, 12, 0, 692000, tzinfo=datetime.timezone.utc)

on older Python versions, you should be able to make use of dateutil's parser:

from dateutil import parser

s = '2020-06-24T10:12:00.692+00:00'

dtobj = parser.isoparse(s)
# - or -
# dtobj = parser.parse(s)

# dtobj
# datetime.datetime(2020, 6, 24, 10, 12, 0, 692000, tzinfo=tzutc())
Related