Python解析日期格式,忽略字符串的部分 [英] Python parse date format, ignore parts of string

查看:209
本文介绍了Python解析日期格式,忽略字符串的部分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要以此格式解析日期,但忽略字符串的部分。 'Wed,27 Oct 1770 22:17:00 GMT'从我收集的内容中,datetime不支持时区。这很好,我只是想忽略字符串的时区部分,而不必对其进行字符串操作。有什么可以用下面的代替%Z来说这里的任何字符串,并解析日期吗?另外,我不明白为什么会解析时间片,如PST,GMT,而不是EST。在任何情况下,似乎都没有附加tzinfo,不知道什么类型的字符串真正寻找%Z部分。

I want' to parse dates in this format, but ignore parts of the string. 'Wed, 27 Oct 1770 22:17:00 GMT' From what I have gathered, datetime does not support time zones very well. Which is fine, I really just want to ignore the timezone part of the string, without having to do string manipulation on it. Is there something I can replace %Z with below to say "any string here" and parse dates as such? Also, I don't understand why it will parse timezones like PST, GMT but not EST. It doesn't seem to attach tzinfo in any case anyways, not sure what types of string its really looking for the %Z portion.

>>> import datetime
>>> y = datetime.datetime.strptime('Wed, 27 Oct 1770 22:17:00 GMT', '%a, %d %b %Y %H:%M:%S %Z')
>>> y = datetime.datetime.strptime('Wed, 27 Oct 1770 22:17:00 PST', '%a, %d %b %Y %H:%M:%S %Z')
>>> y = datetime.datetime.strptime('Wed, 27 Oct 1770 22:17:00 EST', '%a, %d %b %Y %H:%M:%S %Z')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/opt/brazil-pkg-cache/packages/Python/Python-2.5.1.17.1/RHEL5_64/DEV.STD.PTHREAD/build/lib/python2.5/_strptime.py", line 331, in strptime
    (data_string, format))
ValueError: time data did not match format:  data=Wed, 27 Oct 1770 22:17:00 EST  fmt=%a, %d %b %Y %H:%M:%S %Z

注意:dateutil对我来说不是一个选择,想支持多种格式,不能允许dateutil意外地解释日期错误。 (即,dateutil在看到日期如01/02/2010,Feb 1?或Jan 2时似乎猜测到)。我基本上只想尝试接受一个订单中指定的格式,直到我得到一个匹配。

Note: dateutil is not an option for me, I want to support numerous formats and can't allow dateutil to accidentally interpret dates wrong. (i.e. dateutil seems to take a guess when it sees dates like 01/02/2010, Feb 1? or Jan 2?). I basically want to just try accepting formats I specify in an order until I get a match.

推荐答案

val = str.join(' ', 'Wed, 17 Oct 2011 22:22:22 +0300'.split(None)[1:7])

val = datetime.datetime.strptime(val, '%d %b %Y %H:%M:%S')

这篇关于Python解析日期格式,忽略字符串的部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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