我已经花了几个小时,但是我的大脑似乎无法弄清楚,看来我发现的很多信息都适用于Python 2?
import datetime as dt
from datetime import datetime
from pytz import timezone
import pytz
time_stamp = 'Mon, 17 Dec 2018 18:05:01 GMT'
central = timezone('US/Central')
published_time = datetime.strptime(time_stamp, '%a, %d %b %Y %H:%M:%S %Z')
published_cst = published_time.astimezone(central)
actual_time_published = published_cst.strftime('%a, %b %d %Y at %I:%M:%S %p %Z')
print(time_stamp)
print(published_time)
print(published_cst)
print(actual_time_published)
期望acutal_time_published为CST,因为published_cst具有GMT-6小时(第三结果),但这是每个打印命令的实际结果。
Mon, 17 Dec 2018 18:05:01 GMT
2018-12-17 18:05:01
2018-12-17 18:05:01-06:00
Mon, Dec 17 2018 at 06:05:01 PM CST
拔出我的头发!
编辑:是的,出于这个问题的目的,我打算将“ time_stamp”放入“ entry.published”。感谢您的修改!
答案 0 :(得分:2)
我知道了!即使原始时间戳返回了时区(GMT),也没有为其分配tzinfo值(时区值)。即使该字符串包含strptime识别的时区,它仍然是一个“天真”的日期时间。因此,我只是为原始时间分配了UTC的tzinfo值,它似乎可以解决该问题。
time_stamp = 'Mon, 17 Dec 2018 18:05:01 GMT'
utc = timezone('UTC')
central = timezone('US/Central')
published_time = datetime.strptime(time_stamp, '%a, %d %b %Y %H:%M:%S %Z')
published_gmt = published_time.replace(tzinfo=utc)
published_cst = published_gmt.astimezone(central)
actual_time_published = published_cst.strftime('%a, %b %d %Y at %I:%M:%S %p %Z')
所以...
print(time_stamp)
print(published_time)
print(published_cst)
print(actual_time_published)
获得此输出:
Mon, 17 Dec 2018 18:05:01 GMT
2018-12-17 18:05:01
2018-12-17 18:05:01+00:00
2018-12-17 12:05:01-06:00
Mon, Dec 17 2018 at 12:05:01 PM CST