Python 时间老化,第 2 部分:时区

2022-01-16 00:00:00 python datetime timezone

问题描述

继我之前的问题之后,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,但有没有真正的方法可以用 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中实现,我认为您必须手动解析它.

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

相关文章