Python 3.6.2 ValueError: time data does not match format

4.4k Views Asked by At

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.

2

There are 2 best solutions below

2
On BEST ANSWER

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)
0
On

The string you mentioned was a little bit odd. You need to specify the +0000 separately.

>>> strptime('2017-08-07 07:09:31.024719 +0000', '%Y-%m-%d %H:%M:%S.%f %z')
time.struct_time(tm_year=2017, tm_mon=8, tm_mday=7, tm_hour=7, tm_min=9, tm_sec=31, tm_wday=0, tm_yday=219, tm_isdst=-1)