#!/usr/bin/python
# Timezone converter - easy conversion between timezones on the command line
#
# v0.3 (2019/09/18) - http://gagravarr.org/code/
#
# Licensed under the Apache License, Version 2.0, see http://s.apache.org/LIC2

import re
import sys
import pytz
import datetime

# Common aliases for things not in the timezone database
aliases = {
  "IST": "Asia/Calcutta", "IDT": "Asia/Calcutta",
  "BST": "Europe/London", "UK": "Europe/London",
}

# Sanity check
if len(sys.argv) < 5 or not (sys.argv[3] == "in"):
   print "Use:"
   print "   %s <time> <where> in <elsewhere>" % sys.argv[0]
   print "   %s <time> <where> in <elsewhere> on <yyyy-mm-dd>" % sys.argv[0]
   sys.exit(1)

when = sys.argv[1]
where = sys.argv[2]
elsewhere = sys.argv[4]

print "Finding the time in %s when it's %s in %s" % (elsewhere, when, where)

# Did they ask for a specific day?
datefor = None
if len(sys.argv) >= 7 and sys.argv[5] == "on":
    datefor = [int(p) for p in sys.argv[6].split("-")]
    print "Using the date %04d-%02d-%02d" % tuple(datefor)

# Work out the timezones
def to_tz(name):
   if aliases.has_key(name):
      name = aliases[name]
   try:
      return pytz.timezone(name)
   except pytz.exceptions.UnknownTimeZoneError as e:
      for tz in pytz.all_timezones:
         if name in tz:
            return pytz.timezone(tz)
   print "Error, timezone not known - %s" % name
   sys.exit(2)

where_tz = to_tz(where)
elsewhere_tz = to_tz(elsewhere)

print
print "  %s -> %s" % (where, where_tz)
print "  %s -> %s" % (elsewhere, elsewhere_tz)

# Parse the when time
def totime(time):
   if datefor == None:
      d = datetime.datetime.now(tz=where_tz)
   else:
      d = where_tz.localize(datetime.datetime(*datefor))

   hh, mm = None, None
   if time.isdigit():
      hh = int(time)
      mm = 0
   else:
      for sep in (":","."):
         if sep in time:
            hh, mm = [int(t) for t in time.split(sep)]
   if hh:
      return d.replace(hour=hh, minute=mm, second=0, microsecond=0)
   else:
      print "Error - time not in a known format - %s" % time
      sys.exit(3)

wheretime = None

# 12am = 00:00, 12pm = 12:00, special cases
if when.upper().endswith("AM"):
   wheretime = totime(when[0:-2])
   if wheretime.hour == 12:
      wheretime = wheretime + datetime.timedelta(hours=12)
elif when.upper().endswith("PM"):
   wheretime = totime(when[0:-2])
   if not wheretime.hour == 12:
      wheretime = wheretime + datetime.timedelta(hours=12)
else:
   wheretime = totime(when)

theretime = wheretime.astimezone(elsewhere_tz)

def pad(s):
   while len(s) < 15:
      s += " "
   return s
friendly = "%H:%M (%I:%M %p) on %A"

print 
print "Time in %s is  %s" % (pad(where), wheretime)
print "Time in %s is  %s" % (pad(elsewhere), theretime)
print 
print "Time in %s is  %s" % (pad(where), wheretime.strftime(friendly))
print "Time in %s is  %s" % (pad(elsewhere), theretime.strftime(friendly))
