pythonpython-3.xdatetimestrptime

How to parse datetime that ends with `Z`?


I have the following datetime string s:

2017-10-18T04:46:53.553472514Z

I parse it like that:

t = datetime.strptime(s, '%Y-%m-%dT%H:%M:%SZ')

how to fix ValueError: time data '2017-10-18T04:46:53.553472514Z' does not match format '%Y-%m-%dT%H:%M:%SZ'


Solution

  • In theory,

    t = datetime.strptime(s, '%Y-%m-%dT%H:%M:%S.%fZ')
    

    would be the correct format string as you have fractions of second as well. BUT they would then need to be microseconds. Yours are probably nanoseconds, as %f only takes maximum of 6 digits.

    So you need to do something like this:

    t = datetime.datetime.strptime(s.split(".")[0], '%Y-%m-%dT%H:%M:%S')
    t = t + datetime.timedelta(microseconds=int(s.split(".")[1][:-1])/1000)
    
    print (t)
    

    This works but it converts nanoseconds to microseconds. If this is not ok, then you need to do something else.