如何在日期时间模块 python 中获取时区的特定 UTC 时间
how do I get the specific UTC time of a time zone in datetime module python
想获取UTC偏移量+04:30的当前时间,在datetime
模块的文档中找不到可以打开时区时间的函数.我不想使用 pytz
因为我希望我的程序基于用户输入。我该怎么做?
您可以从 timedelta
:
创建静态时区
from datetime import datetime, timezone, timedelta
# let's make this a function so it is more generally useful...
def offset_to_timezone(offset_string):
"""
a function to convert a UTC offset string '+-hh:mm'
to a static time zone.
"""
# check if the offset is forward or backward in time
direction = 1 if offset.startswith('+') else -1
# to hours, minutes, excluding the "direction"
off_hours, off_minutes = map(int, offset[1:].split(':'))
# create a timezone object from the static offset
return timezone(timedelta(hours=off_hours, minutes=off_minutes)*direction)
# you can also make use of datetime's strptime:
def offset_to_tz_strptime(offset_string):
"""
make use of datetime.strptime to do the same as offset_to_timezone().
"""
return datetime.strptime(offset_string, "%z").tzinfo
# call it e.g. as
for offset in ('+04:30', '-04:30'):
tz = offset_to_timezone(offset)
print(f"now at UTC{offset}: {datetime.now(tz).isoformat(timespec='seconds')}")
now at UTC+04:30: 2021-03-28T16:30:21+04:30
now at UTC-04:30: 2021-03-28T07:30:21-04:30
想获取UTC偏移量+04:30的当前时间,在datetime
模块的文档中找不到可以打开时区时间的函数.我不想使用 pytz
因为我希望我的程序基于用户输入。我该怎么做?
您可以从 timedelta
:
from datetime import datetime, timezone, timedelta
# let's make this a function so it is more generally useful...
def offset_to_timezone(offset_string):
"""
a function to convert a UTC offset string '+-hh:mm'
to a static time zone.
"""
# check if the offset is forward or backward in time
direction = 1 if offset.startswith('+') else -1
# to hours, minutes, excluding the "direction"
off_hours, off_minutes = map(int, offset[1:].split(':'))
# create a timezone object from the static offset
return timezone(timedelta(hours=off_hours, minutes=off_minutes)*direction)
# you can also make use of datetime's strptime:
def offset_to_tz_strptime(offset_string):
"""
make use of datetime.strptime to do the same as offset_to_timezone().
"""
return datetime.strptime(offset_string, "%z").tzinfo
# call it e.g. as
for offset in ('+04:30', '-04:30'):
tz = offset_to_timezone(offset)
print(f"now at UTC{offset}: {datetime.now(tz).isoformat(timespec='seconds')}")
now at UTC+04:30: 2021-03-28T16:30:21+04:30
now at UTC-04:30: 2021-03-28T07:30:21-04:30