-
-
Save giansegato/0156699ce3f3a720f2a9380fb1d4fd7c to your computer and use it in GitHub Desktop.
Python script to quickly deal with timezones
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
""" | |
Author: Gian Segato | |
Usage: | |
tz 15 to pt | |
tz: exec name | |
to: either to, or from | |
pt: the desidered timezone | |
15: the desidered time (accepted values: now, +/-x, 15) in the CURRENT timezone if "to", otherwise in the DEST timezone | |
""" | |
import sys | |
import os | |
from datetime import datetime, timedelta | |
import pytz | |
local = pytz.timezone('Europe/Berlin') | |
fmt = '%m-%d %H:%M' | |
if len(sys.argv) != 4: | |
print("Not enough args") | |
os._exit(-1) | |
delta_arg = sys.argv[1] # "16" | |
dir_arg = sys.argv[2].lower() # "to".lower() | |
tz_arg = sys.argv[3].lower() # "pt".lower() | |
tz = None | |
if tz_arg == "pt": | |
tz = "US/Pacific" | |
elif tz_arg == "ct": | |
tz = "US/Central" | |
elif tz_arg == "et": | |
tz = "US/Eastern" | |
elif tz_arg == "uk": | |
tz = "Europe/London" | |
else: | |
raise Exception("Unkonwn timezone") | |
tz = pytz.timezone(tz) | |
to = None | |
if dir_arg == "to": | |
ref = local.localize(datetime.now()) | |
to = tz | |
else: | |
ref = tz.localize(datetime.now()) | |
to = local | |
if delta_arg == "now": | |
delta = 0 | |
elif delta_arg[0] == "+" or delta_arg[0] == "-": | |
delta = int(delta_arg[1:]) | |
if delta_arg[0] == "-": | |
delta *= -1 | |
else: | |
delta = 0 | |
ref = ref.replace(hour=int(delta_arg), minute=0, second=0) | |
ref += timedelta(hours=delta) | |
r = ref.astimezone(to).strftime(fmt) | |
result = "{} ({}) → {} ({})".format(ref.strftime(fmt), tz if to != tz else local, r, local if to != tz else tz) | |
print(result) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment