2015-07-13 48 views
-1

具有下列数据:如何根据给定的开始日期和结束日期过滤包含日期的列表?

dates = ['4/6/2013', '5/4/2013', '6/26/2013', '7/26/2013', '9/5/2013', '10/7/2013', 
     '10/12/2013', '4/12/2014', '5/10/2014', '6/12/2014', '7/19/2014', '8/15/2014', 
     '9/17/2014', '4/21/2015', '5/28/2015', '6/26/2015'] 

如果用户选择start date = 1/1/2014和端date = 12/31/2014 所需的输出应为:

dates = ['4/12/2014', '5/10/2014', '6/12/2014', '7/19/2014', '8/15/2014', '9/17/2014'] 

我新到Python。我写了一些代码,但不能使它工作。请给我一些代码。

+1

请显示您到目前为止尝试过的内容。 –

+1

你好,欢迎来到Stack Overflow。我们一般喜欢它,如果你写一些代码*在这里*。其他地方编写的代码不会帮助你解决问题。 :) – Amadan

+0

检查此[链接](http://stackoverflow.com/questions/5464410/how-to-tell-if-a-date-is-between-two-other-dates-in-python) – The6thSense

回答

3

如果你已经尝试过将日期作为字符串处理,我建议使用datetime

您的字符串日期转换为datetime对象,然后就比较所有日期在开始和结束日期列表:

in_between_dates = [] 
for d in dt_dates: 
    if d >= start_date and d <= end_date: 
     in_between_dates.append(d) 

这里我打印:

from datetime import datetime 

start_date = datetime.strptime('1/1/2014', '%m/%d/%Y') 
end_date = datetime.strptime('12/31/2014', '%m/%d/%Y') 
dates=['4/6/2013', '5/4/2013', '6/26/2013', '7/26/2013', '9/5/2013', '10/7/2013', '10/12/2013', '4/12/2014', '5/10/2014', '6/12/2014', '7/19/2014', '8/15/2014', '9/17/2014', '4/21/2015', '5/28/2015', '6/26/2015'] 

# this line creates a list of datetime objects from the given strings in list dates 
dt_dates = [datetime.strptime(date, '%m/%d/%Y') for date in dates] 

现在有开始和结束的比较输出的字符串格式如下:

print [d.strftime('%m/%d/%Y') for d in in_between_dates] 
# prints: ['04/12/2014', '05/10/2014', '06/12/2014', '07/19/2014', '08/15/2014', '09/17/2014'] 

da的两种主要方法此处使用的tetime分别为strptime and strftime,用于将字符串转换为日期时间对象并将日期时间转换为字符串。

0
from datetime import datetime as dt 

st = "1/1/2014" 
end = "12/31/2014" 

# returns True if d1 is smaller than d2 
def is_smaller(d1, d2): 
    return dt.strptime(d1, "%m/%d/%Y") < dt.strptime(d2, "%m/%d/%Y") 

# returns True if date is in between st and end 
def filter_func(date): 
    return is_smaller(st, date) and is_smaller(date, end) 

dates=['4/6/2013', '5/4/2013', '6/26/2013', '7/26/2013', '9/5/2013', '10/7/2013', '10/12/2013', '4/12/2014', '5/10/2014', '6/12/2014', '7/19/2014', '8/15/2014', '9/17/2014', '4/21/2015', '5/28/2015', '6/26/2015'] 

print(list(filter(filter_func, dates))) 

我刚给你的想法。现在,您可以根据自己的需要进行修改。查找有关filter的更多信息。

0

您可以使用datetime库将日期字符串转换为日期时间对象,以便进行比较。然后,您可以简单地使用列表理解来生成所需日期的列表。

>>>from datetime import datetime 
>>>start_date = datetime.strptime('1/1/2014', '%m/%d/%Y') 
>>>end_date = datetime.strptime('12/31/2014', '%m/%d/%Y') 
>>>dates=['4/6/2013', '5/4/2013', '6/26/2013', '7/26/2013', '9/5/2013', '10/7/2013', '10/12/2013', '4/12/2014', '5/10/2014', '6/12/2014', '7/19/2014', '8/15/2014', '9/17/2014', '4/21/2015', '5/28/2015', '6/26/2015'] 
>>>gooddates = [i for i in dates if start_date < datetime.strptime(i, '%m/%d/%Y') <end_date] 

['4/12/2014', '5/10/2014', '6/12/2014', '7/19/2014', '8/15/2014', '9/17/2014'] 
相关问题