如何根据给定的开始日期和结束日期过滤包含日期的列表

如何根据给定的开始日期和结束日期过滤包含日期的列表

本文介绍了如何根据给定的开始日期和结束日期过滤包含日期的列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

具有以下数据:

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所需的输出应为:

If user selects start date = 1/1/2014 and end date = 12/31/2014the desired output should be:

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

我是Python的新手.我写了一些代码,但无法正常工作.请给我建议一些代码.

I am new to Python. I wrote some code but can't make it work. Please suggest me some code.

推荐答案

如果您尝试将日期作为字符串处理,我建议使用日期时间.

If what you have tried is dealing with dates as strings I would recommend using datetime.

将字符串日期转换为datetime对象,然后将列表中的所有日期与开始日期和结束日期进行比较:

Convert your string dates to datetime objects and then just compare all dates in the list with start and end dates:

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]

现在将开始和结束进行比较:

Now compare with start and end:

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

在这里,我以与给定的相同的字符串格式打印输出:

Here I print the output in the same string format as was given:

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']

此处使用的日期时间的两个主要方法是strftime 分别用于将字符串转换为datetime对象和将datetime转换为字符串.

Two main methods in datetime used here are strptime and strftime used to convert a string to a datetime object and to convert datetime to a string, respectively.

这篇关于如何根据给定的开始日期和结束日期过滤包含日期的列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-01 22:00