How to parse datetime with Z letter with no specified seconds after semicolon

Viewed 443

I'm parsing logs of this program and not accessed to source code of the program.

Log contains an interesting timestamp of event in a log record – 2018-11-02T06:25:03870000Z. It looks strange to me and I don't know how correct is it. But I tend to think that 03974200Z describe a seconds (%s) part and I would like to gather information from this record as much as it possible.

I'm trying to parse this example from Python 3.7 like this:

d = '2018-11-02T06:25:03870000Z'
dt.datetime.strptime(d, '%Y-%m-%dT%H:%M:%S')

It generates a predictable error:

Traceback (most recent call last):
File "<input>", line 1, in <module>
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/_strptime.py", line 577, in _strptime_datetime
tt, fraction, gmtoff_fraction = _strptime(data_string, format)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/_strptime.py", line 362, in _strptime
data_string[found.end():])
ValueError: unconverted data remains: 870000Z

Update: I have dirty solution for this but if there any better approach to do such operation than this:

sc = d.split(':')[-1][:2]
dd = d.split(':')
en = ':'.join(dd[:-1]) 
en += ':' + sc
>> en
'2018-11-02T06:25:03'

Questions:

  1. How to parse such a datetime correctly (determining 03 in the example as a part of seconds)?
  2. (optional) Idk. But is this datetime example in log is correct (in terms of ISO or anything)?
2 Answers

The Z is specifying Zulu Time Zone (UTC or GMT), the seconds are given as whole seconds (03) followed by microseconds (870000) so you can parse the date fully using:

d = '2018-11-02T06:25:03870000Z'
dt.datetime.strptime(d, '%Y-%m-%dT%H:%M:%S%fZ')

I would use

import re
d = '2018-11-02T06:25:03870000Z'
date = re.findall('\d+', d)

this gives you a list of all occurences of one or more digits in a row and now you can do with it what you want, for example

print("Y: %s, M: %s, D: %s, H: %s, m: %s, S: %s" %(tuple(date)))

of course you can then also round the seconds so that they have only two digits

Related