Python pytz 将时间戳(字符串格式)从一个时区转换为另一个时区
我有一个带有字符串格式的时区信息的时间戳,我想将其转换为使用我的本地时区显示正确的日期/时间。因此,对于例如...我已经
timestamp1 = 2011-08-24 13:39:00 +0800
并且想将其转换为时区偏移+1000 到 dsiplay
timestamp2 = 2011-08-24 15:39:00 +1000
我尝试使用 pytz 但找不到很多显示如何使用偏移信息的示例。我在 stackoverflow 上找到的另一个描述这个确切问题的链接是
更新
谢谢 Cixate。我刚刚找到了与你的非常相似的解决方案。发现这些链接很有帮助 - LINK1 和 < a href="https://stackoverflow.com/questions/6729902/python-dateutil-parser-fails">LINK2
发布解决方案以供大家参考
from datetime import datetime
import sys, os
import pytz
from dateutil.parser import parse
datestr = "2011-09-09 13:20:00 +0800"
dt = parse(datestr)
print dt
localtime = dt.astimezone (pytz.timezone('Australia/Melbourne'))
print localtime.strftime ("%Y-%m-%d %H:%M:%S")
2011-09-09 15:20:00
I have a timestamp with timezone information in string format and I would like to convert this to display the correct date/time using my local timezone. So for eg... I have
timestamp1 = 2011-08-24 13:39:00 +0800
and I would like to convert this to say timezone offset +1000 to dsiplay
timestamp2 = 2011-08-24 15:39:00 +1000
I have tried using pytz but couldnt find many examples showing how to use the offset information. One other link that I found on stackoverflow which depicts this exact problem is here. I was hoping there was some better way I could handle this using pytz. Thanks for all suggestions in advance :).
UPDATE
Thanks Cixate. I just found the solution which is very similar to yours. Found these links helpful - LINK1 and LINK2
Posting the solution for everyones benefit
from datetime import datetime
import sys, os
import pytz
from dateutil.parser import parse
datestr = "2011-09-09 13:20:00 +0800"
dt = parse(datestr)
print dt
localtime = dt.astimezone (pytz.timezone('Australia/Melbourne'))
print localtime.strftime ("%Y-%m-%d %H:%M:%S")
2011-09-09 15:20:00
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
datetime.astimezone 将在您获得日期时间后进行基本转换目的。如果您尝试从字符串中获取日期时间对象,请 pip install python-dateutil ,就这么简单作为:
datetime.astimezone will do your basic conversion once you have a datetime object. If you're trying to get a datetime object from a string, pip install python-dateutil and it's as simple as: