gpt4 book ai didi

python - 时区不正确

转载 作者:太空宇宙 更新时间:2023-11-03 14:20:20 28 4
gpt4 key购买 nike

我想在用户输入日期和时间时获取时区。我住在欧洲中部,这里冬季时间为 UTC+001,夏季时间为 UTC+002。问题是,我已经测试过,Python 在冬季和夏季总是给出夏季时间 UTC+002。

示例:

import time

a=time.strptime("13 00 00 30 May 2017", "%H %M %S %d %b %Y")
a_s = time.mktime(a) # to convert in seconds
time.localtime(a_s) #local time
Output>>> time.struct_time(tm_year=2017, tm_mon=5, tm_mday=30, tm_hour=13, tm_min=0, tm_sec=0, tm_wday=1, tm_yday=150, tm_isdst=1)

time.gmtime(a_s) # UTC time
Output>>> time.struct_time(tm_year=2017, tm_mon=5, tm_mday=30, tm_hour=11, tm_min=0, tm_sec=0, tm_wday=1, tm_yday=150, tm_isdst=0)

#Now the Winter
b = time.strptime("13 00 00 20 Dec 2017", "%H %M %S %d %b %Y")
b_s = time.mktime(b)
time.localtime(b_s)
Output>>> time.struct_time(tm_year=2017, tm_mon=12, tm_mday=20, tm_hour=13, tm_min=0, tm_sec=0, tm_wday=2, tm_yday=354, tm_isdst=0)

time.gmtime(b_s)
Output>>>time.struct_time(tm_year=2017, tm_mon=12, tm_mday=20, tm_hour=12, tm_min=0, tm_sec=0, tm_wday=2, tm_yday=354, tm_isdst=0)

time.strftime("%H:%M:%S %z %Z",a)
Output>>>'13:00:00 +0200 Central European Summer Time'

time.strftime("%H:%M:%S %z %Z",b)
Output>>> '13:00:00 +0200 Central European Summer Time' #Wrong should be +0100 and Central European Time

最佳答案

time.strftime('%z %Z', tuple) 返回本地计算机当前使用的 UTC 偏移量和时区缩写的字符串表示形式。它不会尝试找出元组属于哪个时区。

为此需要查找夏令时边界和给定时区对应的 utcoffsets。此信息位于 tz("Olson") database在 Python 中,大多数人都会委托(delegate)这项工作到pytz module .

import time
import datetime as DT
import pytz
FMT = "%H:%M:%S %z %Z"

tz = pytz.timezone('Europe/Berlin')
for datestring in ["13 00 00 30 May 2017", "13 00 00 20 Dec 2017"]:
a = time.strptime(datestring, "%H %M %S %d %b %Y")
a_s = time.mktime(a)
# naive datetimes are not associated to a timezone
naive_date = DT.datetime.fromtimestamp(a_s)
# use `tz.localize` to make naive datetimes "timezone aware"
timezone_aware_date = tz.localize(date, is_dst=None)
print(timezone_aware_date.strftime(FMT))

打印

13:00:00 +0200 CEST
13:00:00 +0100 CET

关于python - 时区不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47980464/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com