Search code examples
pythondatetimestrptime

Python 3.6.2 ValueError: time data does not match format


I am using Python 3.6.2 and am trying to convert this string using time.strptime:

2017-08-07 07:09:31.024719+00:00

which is returned from Active Directory from a query using the ldap3 module.

I issue the following commands:

from time import strptime
strptime('2017-08-07 07:09:31.024719+00:00', '%Y-%m-%d %H:%M:%S.%f%z')

And I get:

ValueError: time data '2017-08-07 07:09:31.024719+00:00' does not match format '%Y-%m-%d %H:%M:%S.%f%z'

According to the documentation, I believe this should work? Also, I intend to add an offset and to this using timedelta and then displaying it to the user in a console.


Solution

  • I've done this in python shell and it seems to solve your problem, if +00:00 meens UTC.

    import datetime.datetime
    date_string = '2017-08-07 07:09:31.024719+00:00'
    date_string = date_string.replace('+00:00','+0000')
    datetime.strptime(date_string, '%Y-%m-%d %H:%M:%S.%f%z')
    

    It returns:

    datetime.datetime(2017, 8, 7, 7, 9, 31, 24719, tzinfo=datetime.timezone.utc)