如何使用UTC偏移量转换字符串 [英] How to convert string with UTC offset

查看:236
本文介绍了如何使用UTC偏移量转换字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有日期为

In [1]: a = "Sun 10 May 2015 13:34:36 -0700"

当我尝试使用 strptime ,其给出错误。

When I try to convert it using strptime, its giving error.

In [3]: datetime.strptime(a, "%a %d %b %Y %H:%M:%S %Z"
   ...: )
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-3-973ef1c6daca> in <module>()
----> 1 datetime.strptime(a, "%a %d %b %Y %H:%M:%S %Z"
      2 )
/usr/lib/python2.7/_strptime.pyc in _strptime(data_string, format)
    323     if not found:
    324         raise ValueError("time data %r does not match format %r" %
--> 325                          (data_string, format))
    326     if len(data_string) != found.end():
    327         raise ValueError("unconverted data remains: %s" %
ValueError: time data 'Sun 10 May 2015 13:34:36 -0700' does not match format '%a %d %b %Y %H:%M:%S %Z'
In [6]: datetime.strptime(a, "%a %d %b %Y %H:%M:%S %z")
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-6-e4870e34edda> in <module>()
----> 1 datetime.strptime(a, "%a %d %b %Y %H:%M:%S %z")
/usr/lib/python2.7/_strptime.pyc in _strptime(data_string, format)
    315                 del err
    316                 raise ValueError("'%s' is a bad directive in format '%s'" %
--> 317                                     (bad_directive, format))
    318             # IndexError only occurs when the format string is "%"
    319             except IndexError:
ValueError: 'z' is a bad directive in format '%a %d %b %Y %H:%M:%S %z'

根据文档,正确的格式是%z ,但可能会丢失一些。

As per doc, correct format is %z, but I might missing some part.

推荐答案

您的格式字符串正确,在Python 3.3中可以正常工作:

Your format string is correct and works fine in Python 3.3:

>>> a = "Sun 10 May 2015 13:34:36 -0700"
>>> datetime.strptime(a, "%a %d %b %Y %H:%M:%S %z")
datetime.datetime(2015, 5, 10, 13, 34, 36, tzinfo=datetime.timezone(datetime.timedelta(-1, 61200)))

它给出了Python 2.7中的错误

It gives the error in Python 2.7 indeed.

strftime()不同,它通过调用libc函数实现, strptime()在Python库中实现。 这里,您可以看到Python 2.7中使用的版本不支持 z 格式。另一方面, here 是Python 3.3中的版本,它支持(我认为这是大约3.2)。

Unlike strftime(), which is implemented by calling the libc function, strptime() is implemented in the Python library. Here you can see that the version used in Python 2.7 doesn’t support the z format. On the other hand here is the version from Python 3.3, which supports that (I think this was added around 3.2).

所以,基本上,你有两个选择:

So, basically, you have two options:


  1. 使用一些能够处理 z 的外部库。

  2. 自己实现(例如通过从字符串中剥离时区,将第一部分提供给 strptime()并手动解析第二部分。看看在Python库中如何做到这一点可能是有帮助的。

  1. Using some external library that is able to handle z.
  2. Implementing it yourself (e.g. by stripping the timezone from the string, feeding the first part to strptime() and parsing the second one manually). Looking at how this is done in the Python library might be helpful.






解析这个以返回一个感知的对象,但这有点复杂。


I tried to parse this to return an "aware" object, but it is somewhat complicated.

>>> a = "Sun 10 May 2015 13:34:36 -0700"
>>> time, tz = a.rsplit(' ', 1)
>>> d = datetime.strptime(time, '%a %d %b %Y %H:%M:%S')
datetime.datetime(2015, 5, 10, 13, 34, 36)

现在我必须调用 d.replace(tzinfo = ... tz ...) c $ c>来替换时区,但问题是我无法获得一个 tzinfo 的实例,因为只知道UTC的偏移量不足以识别时区。

Now I have to call d.replace(tzinfo=…tz…) to replace the timezone, but the problem is that I can’t get an instance of tzinfo because just knowing the offset from UTC is not enough to identify a timezone.

在Python 3.2中有一个特殊的 timezone 类是 tzinfo 的子类,表示假时区仅由其偏移定义。所以有两种方法可以进行:

In Python 3.2 there is a special timezone class that is a subclass of tzinfo representing a "fake" timezone defined by just its offset. So there are two ways to proceed:


  1. Backport(基本上复制并粘贴) timezone class from Python 3,并将其用于解析器。

  2. 返回一个天真对象:

  1. Backport (basically, copy and paste) the timezone class from Python 3 and use it in your parser.
  2. Return a "naive" object:

>>> d + timedelta(hours=int(tz[1:]) * (1 if tz.startswith('-') else -1))
datetime.datetime(2015, 6, 8, 17, 34, 36)


这篇关于如何使用UTC偏移量转换字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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