python - 将字符串 'GMT+5:30' 转换为时区(如 Aisa/Kolkata)而不在 python 中检查 datetime.datetime.now()
问题描述
将字符串 '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)
解决方案
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.
推荐阅读
- python - 在 Windows 上使用 Conda 安装 GDAL
- c++ - 内联静态成员变量
- php - laravel 请求验证数据更新
- python - 在视图中在 django 项目上运行 scrapy
- php - 如何在另一个保管箱中过滤保管箱中的数据?php mysqli
- laravel-5 - 在 laravel 选择框中显示多个变量
- javascript - 基于逻辑 React/Redux 渲染容器
- java - Java Extends RuntimeException 字段值是线程安全的吗?
- monitoring - Promethues 警报规则中的动态标签值
- javascript - @ng-bootstrap/ng-bootstrap NgbModalModule 模态中的 Angula6 ViewChild 返回 undefined