牛魔王的故事
我发现最好的方法是将感兴趣的“时刻”转换为可识别utc-timezone的datetime对象(在python中,datetime对象不需要时区组件)。然后,您可以使用astimezone转换为感兴趣的时区(参考)。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因此,在当地时区(存在的时间)感兴趣的时刻,您可以像这样将其转换为utc(参考)。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")