Search code examples
pythondatetimetimezoneposixoffset

Unix to Timezone Conversion, Offset element


I converted a UNIX timestamp to a human format (sorry I do not know the exact name of it) in a specific timezone (Africa/Algeria) and it evaluated to this: 2020-06-05 19:45:21+01:00. I looked into the datetime module documentation and from what I understood the +01:00, it is the +/-HH:MM offset from the UTC. What I do not understand is why it is returned with the datetime object given it is already converted to the indicated timezone? Could someone explain it to me? Thanks.


Solution

  • POSIX timestamps (Unix time) represent time in seconds since the epoch, 1970-01-01 UTC. No time zone issues involved here. datetime objects on the other hand can be naive (not contain any time zone information) or time zone aware. What you have is a time zone aware datetime object - its string representation prints out as "2020-06-05 19:45:21+01:00". If it had been naive, it would only print "2020-06-05 19:45:21". The repr should also show you a specific time zone, e.g.

    print(repr(dt_obj))
    >>> datetime.datetime(2020, 6, 5, 19, 45, 21, tzinfo=tzfile('Africa/Algiers'))
    

    The important point is that 2020-06-05 19:45:21+01:00 can be converted back to POSIX timestamp without ambiguity:

    from datetime import datetime
    datetime.fromisoformat("2020-06-05 19:45:21+01:00").timestamp()
    # 1591382721.0
    

    If it wasn't for the +01:00 (no tzinfo), Python would assume that the datetime object belongs in local time, i.e. OS setting; meaning that machines in different time zones would get a different timestamp. I'm on UTC+2, so I would get:

    datetime.fromisoformat("2020-06-05 19:45:21").timestamp()
    # 1591379121.0
    

    which gives the same timestamp as

    datetime.fromisoformat("2020-06-05 19:45:21+02:00").timestamp()
    # 1591379121.0
    

    The difference is that with the "+02:00" (tzinfo defined), it is obvious what is happening.