Python时区转换

2022-01-16 00:00:00 python timezone

问题描述

我正在寻找一种快速输入时间的方法,然后 python 将其转换为其他时区(可能多达 10 个不同的时区)

I am looking for a quick way to type in a time and then python convert it into other timezones ( maybe up to 10 different timezones )

对不起.我根本不熟悉python中的时间,如果有人能把我引向正确的方向,我将不胜感激.

Sorry. I am not familar with time in python at all, if someone could put me in the right direction I would really appreciate it.


解决方案

我发现最好的方法是将感兴趣的时刻"转换为支持 utc-timezone 的 datetime 对象(在 python 中,时区组件是datetime 对象不需要).

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).

然后您可以使用 astimezone 转换为感兴趣的时区(参考).

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

from datetime import datetime
import pytz

utcmoment_naive = datetime.utcnow()
utcmoment = utcmoment_naive.replace(tzinfo=pytz.utc)

# print "utcmoment_naive: {0}".format(utcmoment_naive) # python 2
print("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(参考).

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")

相关文章