0

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!

Sad Land
  • 23
  • 3

1 Answers1

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
  • Thanks it worked! Will mark it as an answer in a few minutes! – Sad Land Nov 13 '21 at 09:45
  • 1
    Z (= 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