Search code examples
pythondatetimetimestamputcpython-datetime

utc time string convert to Unix timestamp, and then convert back to utc date time string. But the result is not matched with the original one


I expect 'utc' and 'utc_str_back' should be the same time, but result is diferent. Here is the code:

#input
utc='2023-09-20T05:04:54'

#calculation
utc_time = datetime.strptime(utc, '%Y-%m-%dT%H:%M:%S')
utc_dn = utc_time.timestamp()
utc_back = datetime.fromtimestamp(utc_dn, tz=pytz.utc)
utc_str_back = utc_back.strftime('%Y-%m-%d %H:%M:%S %Z')

#output
utc_str_back ='2023-09-19 21:04:54 UTC'

Solution

  • naive datetime in Python refers to local time, not UTC. Therefore,

    utc_time = datetime.strptime(utc, '%Y-%m-%dT%H:%M:%S')
    

    is misleading; utc_time will be interpreted as local time. That goes wrong in the moment you call

    utc_dn = utc_time.timestamp()
    

    The timestamp method will convert the datetime to UTC, then calculate Unix time (which refers to UTC).


    How to fix it

    docs:

    A naive object does not contain enough information to unambiguously locate itself relative to other date/time objects.

    Your application requires exactly that. So use aware datetime to avoid ambiguities. EX:

    from datetime import datetime, timezone
    
    #input
    utc='2023-09-20T05:04:54'
    
    #calculation
    utc_time = datetime.strptime(utc, '%Y-%m-%dT%H:%M:%S').replace(tzinfo=timezone.utc)
    utc_dn = utc_time.timestamp()
    utc_back = datetime.fromtimestamp(utc_dn, tz=timezone.utc)
    utc_str_back = utc_back.strftime('%Y-%m-%d %H:%M:%S %Z')
    
    #output
    print(utc_str_back)
    # 2023-09-20 05:04:54 UTC
    

    p.s. pytz is deprecated.