将字符串 'GMT+5:30' 转换为时区(如 Aisa/Kolkata)而不检查 python 中的 datetime.datetime.now()
convert string 'GMT+5:30' to Time Zone (like Aisa/Kolkata) without checking datetime.datetime.now() in python
将字符串 'GMT+5:30' 转换为时区(如 Aisa/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)
要为给定的 UTC 偏移量找到匹配的时区,您必须指定一个日期,因为时区的 UTC 偏移量会随着时间而变化,并且它们在某些时期可能有夏令时。时区和 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
的集成更好对象。
将字符串 'GMT+5:30' 转换为时区(如 Aisa/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)
要为给定的 UTC 偏移量找到匹配的时区,您必须指定一个日期,因为时区的 UTC 偏移量会随着时间而变化,并且它们在某些时期可能有夏令时。时区和 DST 源自政治决策,因此它不像拼凑一个 Python 脚本那么容易。
这是一个使用 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 标准库 / datetime
的集成更好对象。