Python Timezone conversion Python Timezone conversion python python

Python Timezone conversion


I have found that the best approach is to convert the "moment" of interest to a utc-timezone-aware datetime object (in python, the timezone component is not required for datetime objects).

Then you can use astimezone to convert to the timezone of interest (reference).

from datetime import datetimeimport pytzutcmoment_naive = datetime.utcnow()utcmoment = utcmoment_naive.replace(tzinfo=pytz.utc)# print "utcmoment_naive: {0}".format(utcmoment_naive) # python 2print("utcmoment_naive: {0}".format(utcmoment_naive))print("utcmoment:       {0}".format(utcmoment))localFormat = "%Y-%m-%d %H:%M:%S"timezones = ['America/Los_Angeles', 'Europe/Madrid', 'America/Puerto_Rico']for tz in timezones:    localDatetime = utcmoment.astimezone(pytz.timezone(tz))    print(localDatetime.strftime(localFormat))# utcmoment_naive: 2017-05-11 17:43:30.802644# utcmoment:       2017-05-11 17:43:30.802644+00:00# 2017-05-11 10:43:30# 2017-05-11 19:43:30# 2017-05-11 13:43:30

So, with the moment of interest in the local timezone (a time that exists), you convert it to utc like this (reference).

localmoment_naive = datetime.strptime('2013-09-06 14:05:10', localFormat)localtimezone = pytz.timezone('Australia/Adelaide')try:    localmoment = localtimezone.localize(localmoment_naive, is_dst=None)    print("Time exists")    utcmoment = localmoment.astimezone(pytz.utc)except pytz.exceptions.NonExistentTimeError as e:    print("NonExistentTimeError")


Using pytz

from datetime import datetimefrom pytz import timezonefmt = "%Y-%m-%d %H:%M:%S %Z%z"timezonelist = ['UTC','US/Pacific','Europe/Berlin']for zone in timezonelist:    now_time = datetime.now(timezone(zone))    print now_time.strftime(fmt)


import datetimeimport pytzdef convert_datetime_timezone(dt, tz1, tz2):    tz1 = pytz.timezone(tz1)    tz2 = pytz.timezone(tz2)    dt = datetime.datetime.strptime(dt,"%Y-%m-%d %H:%M:%S")    dt = tz1.localize(dt)    dt = dt.astimezone(tz2)    dt = dt.strftime("%Y-%m-%d %H:%M:%S")    return dt

-

  • dt: date time string
  • tz1: initial time zone
  • tz2: target time zone

-

> convert_datetime_timezone("2017-05-13 14:56:32", "Europe/Berlin", "PST8PDT")'2017-05-13 05:56:32'> convert_datetime_timezone("2017-05-13 14:56:32", "Europe/Berlin", "UTC")'2017-05-13 12:56:32'

-

> pytz.all_timezones[0:10]['Africa/Abidjan', 'Africa/Accra', 'Africa/Addis_Ababa', 'Africa/Algiers', 'Africa/Asmara', 'Africa/Asmera', 'Africa/Bamako', 'Africa/Bangui', 'Africa/Banjul', 'Africa/Bissau']