Search code examples
pythonutclocaltime

Python: convert localized timestamp to utc timestamp


An external device provides me a titmestamp IN LOCALIZED TIMEZONE. This means I get the number of seconds since 1970 January,1st 00:00:00 IN LOCALTIME.

I need to convert this to UTC timestamp (or any other standard notation) to use it to set the Linux clock (e.g.: "date -s @< timestamp >"). My current TZ is CEST (Europe/Rome), but that might change.

What is the right way to do that?


Solution

  • Just apply to your retrieved timestamp the local time zone's difference from UTC - the easiest way to do that is to use time.altzone (if you don't want to account for DST, use time.timezone instead) and add it to your timestamp, so:

    import time
    
    timestamp = 1532821394  # current CEST timestamp
    utc_timestamp = timestamp + time.altzone  # 1532814194, UTC+2 atm.