Search code examples
python-3.xdatetimetimezoneutc

How to convert a time aware string to its respective UTC format in Python?


All the links I saw were about converting local time to UTC.

But, I have a time aware string 2023-01-24T22:18:00.089-05:00. How do I convert it to its respective UTC format 2023-01-25T03:18:00.089Z in python?


Solution

  • Convert the string to a datetime object (make sure to correctly parse the UTC offset), convert to UTC, then format back to string. For example like

    from datetime import datetime, timezone
    
    print(
          datetime.fromisoformat("2023-01-24T22:18:00.089-05:00") # parse
          .astimezone(timezone.utc) # to UTC
          .isoformat(timespec="milliseconds") # back to ISO 8601 string
          .replace("+00:00", "Z") # UTC as Z
    )
    
    # 2023-01-25T03:18:00.089Z
    

    Note that fromisoformat is a Python 3.7 feature and that there is currently way to directly represent UTC as 'Z' (zulu), so I'm using .replace("+00:00", "Z").