@schlink If it's always an ISO 8601 datetime, you can use `datetime.fromisoformat` (but it looks like you have a Z at the end). If it's always got the Z, you can do:

```
dt_str = dt_str[:-1] + "+00:00"
pub_date = datetime.fromisoformat(dt_str)
```

If it doesn't always have the Z, you can do:

```
if dt_str.endswith("Z"):

dt_str = dt_str[:-1] + "+00:00"
pub_date = datetime.fromisoformat(dt_str)
```

Follow

@schlink Alternatively, there's `dateutil.parser.isoparse`, which will parse any ISO 8601 datetime.

Hopefully before Python 3.11, we'll be able to expand `datetime.fromisoformat` to also be able to parse dates with `Z` at the end (it's a bit more complicated than just that, which is why we haven't done it yet), but until then `dateutil.parser.isoparse` should have you covered.

@schlink I'll note that `datetime.fromisoformat()` is ~75x faster than `datetime.strptime`:

`>>> dt_str = "2021-05-18T19:00:00+00:00"`
`>>> %timeit datetime.fromisoformat(dt_str)
119 ns ± 1.28 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)`
`>>> %timeit datetime.strptime(dt_str, "%Y-%m-%dT%H:%M:%S%z")`
`8.88 µs ± 285 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)`

Sign in to participate in the conversation
Qoto Mastodon

QOTO: Question Others to Teach Ourselves
An inclusive, Academic Freedom, instance
All cultures welcome.
Hate speech and harassment strictly forbidden.