Zac Zac - 1 month ago 14
Python Question

Datetime format for converting a string data into UTC based datetime

I have this date data:

timestamp="2016-11-01T18:18:46.5035795Z"


I am looking for a correct dtfmt so I can convert the data above to a proper datatime value with UTC set as timezone (tzinfo)

dt = datetime.datetime.strptime(timestamp, dtfmt)


Can anybody help ? Thanks

Answer

The dateutil module is ideal for this

pip install python_dateutil

and then

>>> from dateutil import parser
>>> parser.parse(timestamp)
datetime.datetime(2016, 11, 1, 18, 18, 46, 503579, tzinfo=tzutc())

Without the dateutil module you have to use regex to strip out the extra character in the microseconds part of the string, and then use the right date format that matches the string to convert it to a datetime object

>>> import re
>>> timestamp = re.findall('.*[0-9]{6}', timestamp)[0] + 'Z'
>>> datetime.strptime(timestamp, '%Y-%m-%dT%H:%M:%S.%fZ')
datetime.datetime(2016, 11, 1, 18, 18, 46, 503579)