Python pytz 将时间戳(字符串格式)从一个时区转换为另一个时区

发布于 2024-12-03 10:13:59 字数 932 浏览 1 评论 0原文

我有一个带有字符串格式的时区信息的时间戳,我想将其转换为使用我的本地时区显示正确的日期/时间。因此,对于例如...我已经

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

本宫微胖 2024-12-10 10:13:59

datetime.astimezone 将在您获得日期时间后进行基本转换目的。如果您尝试从字符串中获取日期时间对象,请 pip install python-dateutil ,就这么简单作为:

>>> from dateutil.parser import parse
>>> from dateutil.tz import tzoffset
>>> dt = parse('2011-08-24 13:39:00 +0800')
datetime.datetime(2011, 8, 24, 13, 39, tzinfo=tzoffset(None, 28800))
>>> dt.astimezone(tzoffset(None, 3600))
datetime.datetime(2011, 8, 24, 6, 39, tzinfo=tzoffset(None, 3600))

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:

>>> from dateutil.parser import parse
>>> from dateutil.tz import tzoffset
>>> dt = parse('2011-08-24 13:39:00 +0800')
datetime.datetime(2011, 8, 24, 13, 39, tzinfo=tzoffset(None, 28800))
>>> dt.astimezone(tzoffset(None, 3600))
datetime.datetime(2011, 8, 24, 6, 39, tzinfo=tzoffset(None, 3600))
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文