Python老化时间,第2部分:时区 [英] Python time to age, part 2: timezones

查看:58
本文介绍了Python老化时间,第2部分:时区的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

接着我的上一个问题, Python的生存时间 ,我现在遇到了有关时区的问题,事实证明,时区并不总是为 +0200。因此,当strptime试图这样解析它时,它会引发异常。

Following on from my previous question, Python time to age, I have now come across a problem regarding the timezone, and it turns out that it's not always going to be "+0200". So when strptime tries to parse it as such, it throws up an exception.

我考虑过用[:-6]或其他任何东西来截断+0200,但是

I thought about just chopping off the +0200 with [:-6] or whatever, but is there a real way to do this with strptime?

如果重要,我正在使用Python 2.5.2。

I am using Python 2.5.2 if it matters.

>>> from datetime import datetime
>>> fmt = "%a, %d %b %Y %H:%M:%S +0200"
>>> datetime.strptime("Tue, 22 Jul 2008 08:17:41 +0200", fmt)
datetime.datetime(2008, 7, 22, 8, 17, 41)
>>> datetime.strptime("Tue, 22 Jul 2008 08:17:41 +0300", fmt)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python2.5/_strptime.py", line 330, in strptime
    (data_string, format))
ValueError: time data did not match format:  data=Tue, 22 Jul 2008 08:17:41 +0300  fmt=%a, %d %b %Y %H:%M:%S +0200


推荐答案


2.6版中的新功能。

New in version 2.6.

一个天真的对象,%z和%Z
格式代码将替换为空的
字符串。

For a naive object, the %z and %Z format codes are replaced by empty strings.

看起来这仅在> = 2.6中实现,并且我认为您必须手动对其进行解析。

It looks like this is implemented only in >= 2.6, and I think you have to manually parse it.

除了删除时区数据,我看不到其他解决方案:

I can't see another solution than to remove the time zone data:

from datetime import timedelta,datetime
try:
    offset = int("Tue, 22 Jul 2008 08:17:41 +0300"[-5:])
except:
    print "Error"

delta = timedelta(hours = offset / 100)

fmt = "%a, %d %b %Y %H:%M:%S"
time = datetime.strptime("Tue, 22 Jul 2008 08:17:41 +0200"[:-6], fmt)
time -= delta

这篇关于Python老化时间,第2部分:时区的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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