pythonpython-datetime

I have a time in string format, which is of New York. I want the time to be converted to UTC in Python


Input (New York Time in string format) = '2024-11-01 13:00:00'

Output (UTC Time in string format) = '2024-11-01 17:00:00'


Solution

  • Parse the time. It won't be "time zone aware", so apply local time zone, convert to UTC and format again:

    import datetime as dt
    import zoneinfo as zi
    
    zone = zi.ZoneInfo('America/New_York')
    fmt = '%Y-%m-%d %H:%M:%S'
    s = '2024-11-01 13:00:00'
    print(s)
    
    # parse the time and apply the local time zone
    nyt = dt.datetime.strptime(s, fmt).replace(tzinfo=zone)
    
    # convert to UTC and format string
    utc = nyt.astimezone(dt.UTC).strftime(fmt)
    print(utc)
    

    Output:

    2024-11-01 13:00:00
    2024-11-01 17:00:00