首页 > 解决方案 > 将字符串 'GMT+5:30' 转换为时区(如 Ais​​a/Kolkata)而不在 python 中检查 datetime.datetime.now()

问题描述

将字符串 'GMT+5:30' 转换为时区(如 Ais​​a/Kolkata)而不在 python 中检查 datetime.datetime.now()

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)

标签: pythondatetimepytz

解决方案


To find matching timezones for a given UTC offset you must specify a date since the UTC offset of timezones changes over time and they might have DST during certain periods. Timezones and DST originate from political decisions so it's not as easy as hacking together a Python script.

Here's an example to find timezones with UTC+5:30 using 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']

You could replace datetime.datetime.now with any date of your choice.

Same result using 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']

Note that pytz is more efficient in getting UTC offsets, however I'd prefer dateutil due to its better integration with the Python standard lib / datetime objects.


推荐阅读