使用以下数据:
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新手。我写了一些代码,但无法使其工作。请给我一些代码。
答案 0 :(得分:4)
如果您尝试过将日期作为字符串处理,我建议您使用datetime。
将字符串日期转换为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']
# 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]
现在与开始和结束进行比较:
in_between_dates = []
for d in dt_dates:
if d >= start_date and d <= end_date:
in_between_dates.append(d)
这里我以与给定的相同的字符串格式打印输出:
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']
此处使用的日期时间中的两个主要方法是strptime
and strftime
,用于将字符串转换为日期时间对象并将日期时间转换为字符串。
答案 1 :(得分:1)
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。
的更多信息答案 2 :(得分:0)
您可以使用datetime库将日期字符串转换为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']