python时间到第二部分,时区 [英] python time to age part 2, timezones

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

问题描述

从以前的问题开始: Python时间到达

我现在遇到有关时区的问题,原来它并不总是+0200。
所以当strptime尝试解析它时,它会引发一个异常。

I have now come across a problem regarding the timezone, turns out that its not always going to be "+0200". So when strptime tries to parse it as such, it throws up an exception.

我想到只需用[:-6]或者什么,但是有什么真正的方式来做到这一点与strptime?

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中实现,我想你必须手动解析它。

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

我看不到另一个解决方案,而不是删除时区数据。 $ p

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时间到第二部分,时区的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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