I have a datetime string like this: 2021-11-13T09:20:15.497Z
, I'm just wondering how can I convert this into a datetime object?
I tried datetime.datetime.fromiso()
but it told me that the format is not an iso format
Thanks in advance!
Asked
Active
Viewed 1,774 times
0

Sad Land
- 23
- 3
-
[efficient work-around](https://stackoverflow.com/a/62769371/10197418) to use `fromisoformat` – FObersteiner Nov 13 '21 at 09:47
1 Answers
1
Use "%Y-%m-%dT%H:%M:%S.%f%z"
format
from datetime import datetime
x = datetime.strptime("2021-11-13T09:20:15.497Z", "%Y-%m-%dT%H:%M:%S.%f%z")
print(x) # 2021-11-13 09:20:15.497000+00:00
print(x.isoformat()) # 2021-11-13T09:20:15.497000+00:00

azro
- 53,056
- 7
- 34
- 70
-
-
1Z (= UTC) should not be ignored by using a literal Z in the parsing directive. Why? Because it gives you naive datetime, which Python treats as local time, which is most likely not UTC. You can use %z in the directive. – FObersteiner Nov 13 '21 at 09:46