0

An API is providing a time stamp in the following format

s = "2023-02-02T21:05:07.2207121Z"`

I'm attempting to convert it to a datetime object

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

It's causing the following error

line 349, in _strptime
    raise ValueError("time data %r does not match format %r" %
ValueError: time data '2023-02-02T21:05:07.2207121Z' does not match format '%Y-%m-%dT%H:%M:%S.%fZ'

This question was marked as a duplicated linked to a post suggesting fromisoformat(s), but that fails as well

dt = datetime.fromisoformat(s)

error

    dt = datetime.fromisoformat(s)
ValueError: Invalid isoformat string: '2023-02-02T21:05:07.2207121Z'
Michael Moreno
  • 947
  • 1
  • 7
  • 24
  • 1
    I suspect the `%f` accepts only 6 digits, so try `dt = datetime.strptime(s[:-2], "%Y-%m-%dT%H:%M:%S.%f")` – Andrej Kesely Feb 02 '23 at 21:58
  • yes, `%f` in Python only takes 6 digits of fractional seconds (microsecond precision). Simplest option might be using [dateutils](https://dateutil.readthedocs.io/en/stable/parser.html) `parser.parse` or `parser.isoparse`, which truncates to microseconds for you *and* considers Z to be UTC. – FObersteiner Feb 03 '23 at 04:10

0 Answers0