如何在datetime模块python中获取时区的特定UTC时间
我想获取UTC偏移量+04:30中的当前时间,但在如何在datetime模块python中获取时区的特定UTC时间,python,datetime,timezone,Python,Datetime,Timezone,我想获取UTC偏移量+04:30中的当前时间,但在datetime模块的文档中找不到任何可以打开时区时间的函数。我不想使用pytz,因为我想要基于用户输入的程序。我该怎么做呢?您可以从时间增量创建一个静态时区: from datetime import datetime, timezone, timedelta # let's make this a function so it is more generally useful... def offset_to_timezone(offset
datetime
模块的文档中找不到任何可以打开时区时间的函数。我不想使用pytz
,因为我想要基于用户输入的程序。我该怎么做呢?您可以从时间增量
创建一个静态时区:
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')}")
您还可以考虑让用户选择,然后使用pytz或(Python 3.9+)将其转换为时区对象。我编辑了一些代码,这样就可以将+04:30的时间去掉,效果非常好@珀特:很高兴这有帮助。顺便说一句,我添加了一个更方便的选项。
now at UTC+04:30: 2021-03-28T16:30:21+04:30
now at UTC-04:30: 2021-03-28T07:30:21-04:30