Python函数返回uncode字符串而不是datetime对象

时间:2016-06-24 00:12:43

标签: python datetime

我有解决这个问题的方法,但我想知道它为什么会出问题。 在下面的代码中,filter函数是一个unicode字符串列表,而不是is_date_string生成的datetime对象

import re
import requests

datestrings = re.compile(r'\d*-\d*-\d* \d*:\d*:\d*')

def is_date_string(s):
    try:
        return datetime.datetime.strptime(s, '%Y-%m-%d %H:%M:%S')
    except:
        return False

d = filter(is_date_string,datestrings.findall(request.text))

这是正则表达式产生的数据样本:

 DATESTRINGS = 
    [u'2016-06-24 05:36:42', u'2016-06-24 04:53:02', u'2016-06-24 04:53:02', u'2016-06-24 04:53:02', u'2016-06-24 04:53:02', u'2016-06-24 04:53:02', u'2016-06-24 04:53:02', u'2016-06-24 04:53:03', u'2016-06-24 04:53:04', u'2016-06-24 04:53:04', u'2016-06-24 04:53:04', u'2016-06-24 04:53:05', u'2016-06-24 04:53:05', u'2016-06-24 04:53:05', u'2016-06-24 04:53:05', u'2016-06-24 04:53:05', u'2016-06-24 04:53:05', u'2016-06-24 04:53:05', u'2016-06-24 04:53:05', u'2016-06-24 04:53:05', u'2016-06-24 04:53:05', u'2016-06-24 04:53:05', u'2016-06-24 04:53:05', u'2016-06-24 04:53:05', u'2016-06-24 04:53:05', u'2016-06-24 04:53:05', u'2016-06-24 04:53:05', u'2016-06-24 04:53:05', u'2016-06-24 04:53:05', u'2016-06-24 04:53:05', u'2016-06-24 04:53:05', u'2016-06-24 04:53:05', u'2016-06-24 04:53:05', u'2016-06-24 04:53:05', u'2016-06-24 04:53:05', u'2016-06-24 04:53:05', u'2016-06-24 04:53:05', u'2016-06-24 04:53:05', u'2016-06-24 04:53:05', u'2016-06-24 04:53:05', u'2016-06-24 04:53:05', u'2016-06-24 04:53:05', u'2016-06-24 04:53:05', u'2016-06-24 04:53:05', u'2016-06-24 04:53:05', u'2016-06-24 04:53:05', u'2016-06-24 04:53:05', u'2016-06-24 04:53:05', u'2016-06-24 04:53:05', u'2016-06-24 04:53:05', u'2016-06-24 04:53:05', u'2016-06-24 04:53:05', u'2016-06-24 04:53:', u'2016-06-24 05:18:56', u'2016-06-24 05:36:43', u'2016-06-27 05:00:00']

我的工作是d的列表理解,以执行函数应该做的事情

dates = [datetime.datetime.strptime(x, '%Y-%m-%d %H:%M:%S') for x in d if x] 

但是问题是关于is_date_string函数没有返回datetime对象。为什么呢?

1 个答案:

答案 0 :(得分:5)

过滤器使用函数的结果进行过滤,但返回是iterable的子集,在您的情况下是一个字符串。

你想要的东西似乎是这样的

d = filter(None, map(is_date_string,datestrings.findall(request.text)))

https://docs.python.org/2/library/functions.html#filter 来自doc

  

请注意,如果函数不是[item for item in iterable if function(item)],则过滤器(函数,可迭代)等效于None,如果函数是[item for item in iterable if item],则过滤器等效于None