Python: convert localized timestamp to utc timestamp

Clash Royale CLAN TAG#URR8PPPPython: 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?
2 Answers
2
You can add/take the difference between your current timezone and UTC in seconds.
For example, if your are in CEST, then this is UTC+2, so you can simply do:
utc = timestamp + (-1 * 2 * 60 * 60)
60 minutes in an hour, 60 seconds in a minute, 2 because we are 2 hours away from UTC and -1 because we are ahead of it.
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:
time.altzone
time.timezone
import time
timestamp = 1532821394 # current CEST timestamp
utc_timestamp = timestamp + time.altzone # 1532814194, UTC+2 atm.
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.