在python中,无需检查datetime.datetime.now(),即可将字符串 "GMT+5:30 "转换为时区(如AisaKolkata)。

问题描述 投票:0回答:1

在python中,无需检查datetime.datetime.now(),即可将字符串 "GMT+5:30 "转换为时区(如AisaKolkata)。

now = datetime.datetime.astimezone(Time_Zone).tzname()  # current time
print(now)
print(type(now))
utc_offset = datetime.timedelta(hours=5, minutes=30)  # +5:30
print(utc_offset)
for tz in map(pytz.timezone, pytz.all_timezones_set):
    if (now.astimezone(tz).utcoffset() == utc_offset):
        print(tz.zone)
python datetime pytz
1个回答
0
投票

要为给定的UTC偏移找到匹配的时区,你必须指定一个日期,因为时区的UTC偏移会随着时间的推移而改变,而且在某些时期可能会有DST。时区和DST源于政治决定,所以它不像黑客编写Python脚本那么简单。

下面是一个使用以下代码来查找UTC+5:30的时区的例子 dateutil:

import datetime
from dateutil.tz import gettz
from dateutil.zoneinfo import get_zonefile_instance

offset, match_offset = int(60*60*5.5), []

for z in get_zonefile_instance().zones:
    off = datetime.datetime.now(tz=gettz(z)).utcoffset()
    if int(off.total_seconds()) == offset:
        match_offset.append(z)

print(match_offset)
# ['Asia/Calcutta', 'Asia/Colombo', 'Asia/Kolkata']

你可以更换 datetime.datetime.now 与您选择的任何日期。

同样的结果,使用 pytz:

import pytz

offset, match_offset = int(60*60*5.5), []

for z in pytz.all_timezones:
    off = datetime.datetime.now(tz=pytz.timezone(z)).utcoffset()
    if int(off.total_seconds()) == offset:
        match_offset.append(z)

print(match_offset)
# ['Asia/Calcutta', 'Asia/Colombo', 'Asia/Kolkata']

注意: pytz 在获取UTC偏移方面更有效,但我更喜欢用 dateutil 由于它与Python标准的lib datetime 对象。

© www.soinside.com 2019 - 2024. All rights reserved.