【问题标题】:convert string 'GMT+5:30' to Time Zone (like Aisa/Kolkata) without checking datetime.datetime.now() in python将字符串 'GMT+5:30' 转换为时区(如 Ais​​a/Kolkata)而不在 python 中检查 datetime.datetime.now()
【发布时间】:2020-09-22 14:55:29
【问题描述】:

将字符串 '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)

【问题讨论】:

标签: python datetime pytz


【解决方案1】:

要为给定的 UTC 偏移量查找匹配的时区,您必须指定一个日期,因为时区的 UTC 偏移量会随时间而变化,并且它们在某些时期可能具有 DST。时区和 DST 源于政治决策,因此它不像编写 Python 脚本那么容易。

这是一个使用 dateutil 查找 UTC+5:30 时区的示例:

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 标准库/datetime 对象更好地集成。

【讨论】:

    猜你喜欢
    • 2014-06-07
    • 1970-01-01
    • 2019-11-25
    • 1970-01-01
    • 2018-02-04
    • 2016-04-07
    • 2019-01-02
    • 2019-05-21
    • 1970-01-01
    相关资源
    最近更新 更多