0

I need to convert a time given by the user (as a string) to UTC depending on the timezone the user is in. So all I need is the offset of the timezone (considering daylight saving time) to UTC. The problem seems to be, that there is no builtin timezone info in python, so I need to require pytz (which I'd rather not). Is there an easier way?

from datetime import datetime
import pytz

TIME_FORMAT = '%H:%M:%S'
TIMEZONE = 'Europe/Berlin'


def utctime_for_timestring(timestring, tz=TIMEZONE, tfmt=TIME_FORMAT):
    t = datetime.strptime(timestring, tfmt)
    offset = datetime.now(pytz.timezone(tz)).utcoffset()
    return (t - offset).time()


#  >>> utctime_for_timestring('20:00:00')
# datetime.time(18, 0)
Dill
  • 1,943
  • 4
  • 20
  • 28
  • 1
    pytz is your friend – Will May 30 '19 at 22:24
  • @Will I don't like friends. (I'd rather not introduce a dependency) – Dill May 30 '19 at 22:31
  • 1
    To handle timezone conversions properly, you cannot rely on python's builtin datetime module https://stackoverflow.com/questions/4530069/python-how-to-get-a-value-of-datetime-today-that-is-timezone-aware – Will May 30 '19 at 22:42

0 Answers0