24h*_*ast 2 python timezone datetime pytz python-3.x
我花了几个小时在这上面,但我的大脑似乎无法弄清楚,而且我发现的很多信息似乎都适用于 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)
Run Code Online (Sandbox Code Playgroud)
预计 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
Run Code Online (Sandbox Code Playgroud)
拔我的头发!
编辑:是的,出于这个问题的目的,我有“entry.published”,我打算在其中放置“time_stamp”。感谢您的编辑!
我想到了!尽管原始时间戳返回时区 (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')
Run Code Online (Sandbox Code Playgroud)
所以...
print(time_stamp)
print(published_time)
print(published_cst)
print(actual_time_published)
Run Code Online (Sandbox Code Playgroud)
产生这个输出:
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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
10314 次 |
| 最近记录: |