0

I'm parsing timestamp of event in a log record – 2020-08-09T03:37:33.358874554Z. It looks strange to me and I don't know how correct is it. I don'think that 358874554 describe. I'm trying to parse this example from Python 3.7 like this:

dt.datetime.strptime('2020-08-09T03:37:33.358874554Z', "%Y-%m-%dT%H:%M:%S.%fZ")

It generates an error:

ValueError: time data '2020-08-09T03:37:33.358874554Z' does not match format '%Y-%m-%dT%H:%M:%S.%fZ'

How to parse such a datetime correctly? Is this datetime example in log is correct (in terms of ISO or anything)?

LeMoussel
  • 5,290
  • 12
  • 69
  • 122
  • Right, use `fromisoformat`. `Z` is not a fix letter, you should be able to read any time offset. – Giacomo Catenazzi May 05 '21 at 14:05
  • Don't run. I do `dt.datetime.fromisoformat('2020-08-09T03:37:33.358874554Z'.replace('Z', '+00:00'))`. I get error `Invalid isoformat string: '2020-08-09T03:37:33.358874554+00:00'` It's seem to be RFC1123 date and time string. – LeMoussel May 05 '21 at 14:25
  • Note that `pandas.to_datetime` will parse to datetime **including the nanoseconds**; e.g. `pd.to_datetime('2020-08-09T03:37:33.358874554Z')` gives `Timestamp('2020-08-09 03:37:33.358874554+0000', tz='UTC')`. – FObersteiner May 05 '21 at 15:21

2 Answers2

1

You can use the dateutil.parser Like this:

>>>>import dateutil.parser as p
>>>>p.parse('2020-08-09T03:37:33.358874554Z')
datetime.datetime(2020, 8, 9, 3, 37, 33, 358874, tzinfo=tzutc())
0

You should use dateutil module as an alternative:

$ pip install python-dateutil
>>> import dateutil.parser
>>> dateutil.parser.isoparse('2020-08-09T03:37:33.358874554Z')
datetime.datetime(2020, 8, 9, 3, 37, 33, 358874, tzinfo=tzutc())
Corralien
  • 109,409
  • 8
  • 28
  • 52