Search code examples
pythonpython-3.xdatetimeunix-timestamp

How to convert string datetime to UTC UNIX?


I have date in the as string in the following format: 202001010000

I am trying to convert this to UNIX format and get the result in UTC

I did:

import datetime

stime = "202001010000"

print(int(datetime.datetime.strptime(stime, "%Y%m%d%H%M").replace(tzinfo=datetime.timezone.utc).timestamp()))

and this is giving me the output in UNIX, but in CEST format.

With the above code I get: 1577836800 but I want the output to be 1577833200

What is the mistake I am doing?


Solution

  • You're setting time zone to UTC when converting to datetime. But since your input represents time in Germany you want a time zone that is active there. EX:

    from datetime import datetime
    from zoneinfo import ZoneInfo # Python 3.9+, can use backports.zoneinfo for older versions
    
    stime = "202001010000"
    # stime represents time in Germany so we use time zone
    time_zone = ZoneInfo('Europe/Berlin')
    
    # to datetime, with tz set:
    dtobj = datetime.strptime(stime, "%Y%m%d%H%M").replace(tzinfo=time_zone)
    
    # unix time
    ts = dtobj.timestamp()
    print(ts)
    # 1577833200.0
    
    # back to datetime, again specify time zone
    dtobj = datetime.fromtimestamp(ts, tz=time_zone)
    print(dtobj)
    # 2020-01-01 00:00:00+01:00
    

    Note that if the input represents the same time zone your OS is configured to use, this works correctly without setting a time zone. But I think it's better to be explicit here, to avoid confusion if you e.g. run this script on a machine configured to use another time zone.