Search code examples
pythondatetimeunixutc

Python convert timestamp to unix


I know these questions have been asked before but I'm struggling to convert a timestamp string to a unix time and figuring out whether the datetime objects are naive or aware

For example, to convert the time "2021-05-19 12:51:47" to unix:

>>> from datetime import datetime as dt
>>> dt_obj = dt.strptime("2021-05-19 12:51:47", "%Y-%m-%d %H:%M:%S")
>>> dt_obj
datetime.datetime(2021, 5, 19, 12, 51, 47)

is dt_obj naive or aware and how would you determine this? The methods on dt_obj such as timetz, tzinfo, and tzname don't seem to indicate anything - does that mean that dt_obj is naive?

Then to get unix:

>>> dt_obj.timestamp()
1621421507.0

However when I check 1621421507.0 on say https://www.unixtimestamp.com then it tells me that gmt for the above is Wed May 19 2021 10:51:47 GMT+0000, ie 2 hours behind the original timestamp?


Solution

  • since Python's datetime treats naive datetime as local time by default, you need to set the time zone (tzinfo attribute):

    from datetime import datetime, timezone
    
    # assuming "2021-05-19 12:51:47" represents UTC:
    dt_obj = datetime.fromisoformat("2021-05-19 12:51:47").replace(tzinfo=timezone.utc)
    

    Or, as @Wolf suggested, instead of setting the tzinfo attribute explicitly, you can also modify the input string by adding "+00:00" which is parsed to UTC;

    dt_obj = datetime.fromisoformat("2021-05-19 12:51:47" + "+00:00")
    

    In any case, the result

    dt_obj.timestamp()
    # 1621428707.0
    

    now converts as expected on https://www.unixtimestamp.com/: enter image description here