Search code examples
pythonstringdatetimeiso

How do I convert type of a datetime string which has Z in it


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!


Solution

  • 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