Python strptime()和时区? [英] Python strptime() and timezones?

查看:88
本文介绍了Python strptime()和时区?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个来自Blackberry IPD备份的CSV转储文件,使用IPDDump创建。
这里的日期/时间字符串看起来像这样
(其中 EST 是澳大利亚时区):

  Tue Jun 22 07:46:22 EST 2010 

我需要能够在Python中解析这个日期。起初,我试图使用datettime中的 strptime()函数。

 >>> datetime.datetime.strptime('Tue Jun 22 12:10:20 2010 EST','%a%b%d%H:%M:%S%Y%Z')

但是,由于某些原因,返回的 datetime 对象似乎没有任何 tzinfo 与之相关。



我在这个页面,显然 datetime.strptime 默认丢弃 tzinfo ,但是,我检查了文档,我找不到任何这样的记录这里



我已经能够使用第三方Python库解析日期, dateutil ,但是我仍然很好奇我如何使用内置的 strptime()不正确?有没有办法得到 strptime()可以很好地使用时区?

解决方案

datetime 模块文档说:


返回对应于date_string的datetime,根据格式进行解析。这相当于 datetime(*(time.strptime(date_string,format)[0:6]))


看到 [0:6] ?这让你(年,月,日,小时,分,秒)。没有其他的。没有提到时区。



有趣的是,[Win XP SP2,Python 2.6,2.7]将您的示例传递给 time.strptime 不工作,但如果你脱掉%Z和EST,它的工作。也使用UTC或GMT而不是EST作品。 PST和MEZ不起作用困惑。


I have a CSV dumpfile from a Blackberry IPD backup, created using IPDDump. The date/time strings in here look something like this (where EST is an Australian time-zone):

Tue Jun 22 07:46:22 EST 2010

I need to be able to parse this date in Python. At first, I tried to use the strptime() function from datettime.

>>> datetime.datetime.strptime('Tue Jun 22 12:10:20 2010 EST', '%a %b %d %H:%M:%S %Y %Z')

However, for some reason, the datetime object that comes back doesn't seem to have any tzinfo associated with it.

I did read on this page that apparently datetime.strptime silently discards tzinfo, however, I checked the documentation, and I can't find anything to that effect documented here.

I have been able to get the date parsed using a third-party Python library, dateutil, however I'm still curious as to how I was using the in-built strptime() incorrectly? Is there any way to get strptime() to play nicely with timezones?

解决方案

The datetime module documentation says:

Return a datetime corresponding to date_string, parsed according to format. This is equivalent to datetime(*(time.strptime(date_string, format)[0:6])).

See that [0:6]? That gets you (year, month, day, hour, minute, second). Nothing else. No mention of timezones.

Interestingly, [Win XP SP2, Python 2.6, 2.7] passing your example to time.strptime doesn't work but if you strip off the " %Z" and the " EST" it does work. Also using "UTC" or "GMT" instead of "EST" works. "PST" and "MEZ" don't work. Puzzling.

这篇关于Python strptime()和时区?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆