如何从Python中包含“2nd”的字符串获取日期时间? [英] How to get the datetime from a string containing '2nd' for the date in Python?

查看:333
本文介绍了如何从Python中包含“2nd”的字符串获取日期时间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有几个字符串,我想从中获取日期时间。它们的格式如下:

  2013年5月2日19:00 
pre>

我几乎知道如何将其转换为日期时间,除了我遇到了2 nd 的问题。我现在有以下

 >>> datetime.strptime('Thu 02 May 2013 19:00','%a%d%B%Y%H:%M')
datetime.datetime(2013,5,2,19,0)

这个月份的日子,零填充号码可以正常工作,但是当我尝试 2nd ,它给出一个ValueError:

 >>> datetime.strptime('Thu 2nd May 2013 19:00','%a%d%B%Y%H:%M')
追溯(最近呼叫最后):
文件<输入>,第1行在< module>
(data_string,format))
ValueError:时间数据'Thu 2013年5月2日19:00'与格式不一致%a%d%B%Y%H:%M'

datetime伪指令我找不到有关日期的有序值(1st,2nd,3rd等)的任何内容。有人知道我能得到这个工作吗?欢迎所有提示!

解决方案

考虑使用 dateutil.parser.parse



这是第三个有一个强大的解析器可以处理这些东西的派对库。

  from dateutil.parser import parse 

s ='Thu 2013年5月2日19:00'

d = parse(s)
print(d,type(d))
#2013-05-02 19 :00:00< class'datetime.datetime'>

一个简短的警告(在你的情况下并不会发生):if dateutil 在字符串中找不到日期的一个方面(比如说你省去了一个月),那么它将默认为默认值参数。默认为当前日期,时间为00:00:00。如果需要,您可以使用不同的 datetime 对象重写这个。



安装 dateutil 可能是使用 pip 使用命令 pip install python-dateutil


I've got a couple strings from which I want to get the datetime. They are formatted like this:

Thu 2nd May 2013 19:00

I know almost how I can convert this to a datetime, except for that I'm having trouble with the "2nd". I now have the following

>>> datetime.strptime('Thu 02 May 2013 19:00', '%a %d %B %Y %H:%M')
datetime.datetime(2013, 5, 2, 19, 0)

which works fine with a zero padded number for the day of the month, but when I try the 2nd, it gives a ValueError:

>>> datetime.strptime('Thu 2nd May 2013 19:00', '%a %d %B %Y %H:%M')
Traceback (most recent call last):
  File "<input>", line 1, in <module>
    (data_string, format))
ValueError: time data 'Thu 2nd May 2013 19:00' does not match format '%a %d %B %Y %H:%M'

In the list of datetime directives I can't find anything relating to ordered values (1st, 2nd, 3rd etc) for dates. Does anybody know how I can get this to work? All tips are welcome!

解决方案

Consider using dateutil.parser.parse.

It's a third party library that has a powerful parser which can handle these kinds of things.

from dateutil.parser import parse

s = 'Thu 2nd May 2013 19:00'

d = parse(s)
print(d, type(d))
# 2013-05-02 19:00:00 <class 'datetime.datetime'>

A brief caveat (doesn't really occur in your case): if dateutil can't find an aspect of your date in the string (say you leave out the month) then it will default to the default argument. This defaults to the current date with the time 00:00:00. You can obviously over-write this if necessary with a different datetime object.

The easiest way to install dateutil is probably using pip with the command pip install python-dateutil.

这篇关于如何从Python中包含“2nd”的字符串获取日期时间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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