Python将所有日期时间对象(日期)拉出来

时间:2014-04-27 06:48:31

标签: python regex datetime

import datetime

a=[datetime.datetime(2014, 4, 13, 0, 0), u'a', u'b', u'c',datetime.datetime(2014, 4, 14, 0, 0), u'a', u'b', u'c', datetime.datetime(2014, 4, 15, 0, 0), u'a', u'b', u'c']

如何从此列表中提取所有日期?

我总是可以循环测试。但我该如何做得更好?

我可以使用正则表达式,就像我在这里python regular expression, pulling all letters out一样。但我知道有更有效的方法。

我在这里查看了https://docs.python.org/2/library/stdtypes.html,但它看起来并不像datetime对象是内置类型。所以我想我无法走那条路。其他建议请。

注意:我不知道日期是否为每4个值。我需要一些无论模式的东西。

2 个答案:

答案 0 :(得分:4)

我们知道你想要的类型是datetime.datetime,所以写一个列表理解似乎是最干净的方法(不用担心模式):

b = [i for i in a if type(i) == datetime.datetime]

我怀疑你可以使用正则表达式(除非你将所有内容都转换为字符串),除非你选择将每个datetime转换为stringunicode表示形式,并且无论如何,你正在检查类型......

>>> print [type(i) for i in a]
[<type 'datetime.datetime'>, <type 'unicode'>, <type 'unicode'>, <type 'unicode'>, <type 'datetime.datetime'>, <type 'unicode'>, <type 'unicode'>, <type 'unicode'>, <type 'datetime.datetime'>, <type 'unicode'>, <type 'unicode'>, <type 'unicode'>]

答案 1 :(得分:0)

查看您的代码,您的列表似乎如下:

a = [date, x, x, x, date, x, x, x, date, x, ...]

为此你可以这样做:

b = a[::4]

然后将每个datetime对象格式化为您想要的任何模式。