假设我有一个日期列表:
dates =['11/09/2013','12/09/2013','20/09/2013','27/09/2013','30/09/2013']
test = '21/09/2013'
我想根据这个'测试'变量
拆分'日期'列表期望的输出:
1. ['11/09/2013','12/09/2013','20/09/2013']
2. ['27/09/2013','30/09/2013']
如果'test'实际上属于(包含)在列表中,它必须在列表1中。
我正在尝试一切仍然没有运气。
答案 0 :(得分:0)
如何将项目转换为datetime对象?
from datetime import datetime
# convert to datetime objects
datesdt = [datetime.strptime(date, '%d/%m/%Y') for date in dates]
testdt = datetime.strptime(test, '%d/%m/%Y')
# make separate datetime object lists for low and high dates
low_date_dt_list = [dt for dt in datesdt if dt <= testdt]
high_date_dt_list = [dt for dt in datesdt if dt > testdt]
# now print in desired format
low_date_list = [dt.strftime('%d/%m/%Y') for dt in low_date_dt_list]
high_date_list = [dt.strftime('%d/%m/%Y') for dt in high_date_dt_list]
以下是使用上述代码与您的dates
和test
值相符时输出的内容:
In [27]: low_date_list
Out[27]: ['11/09/2013', '12/09/2013', '20/09/2013']
In [28]: high_date_list
Out[28]: ['27/09/2013', '30/09/2013']
datetime.strptime
strftime
答案 1 :(得分:0)
您应该将字符串转换为datetime对象,然后使用日期比较拆分列表:
from datetime import datetime
dates =['11/09/2013','12/09/2013','20/09/2013','27/09/2013','30/09/2013']
test = '21/09/2013'
# Convert to datetime objects
dd = [datetime.strptime(d,'%d/%m/%Y') for d in dates]
tt = datetime.strptime(test,'%d/%m/%Y')
# Split lists
dd_before = [d for d in dd if d < tt]
dd_after = [d for d in dd if d >= tt]
# Convert back to strings if needed
dates_before = [datetime.strftime(d,'%d/%m/%Y') for d in dd_before]
dates_after = [datetime.strftime(d,'%d/%m/%Y') for d in dd_after]
答案 2 :(得分:0)
dates =['11/09/2013','12/09/2013','20/09/2013','27/09/2013','30/09/2013']
test = '21/09/2013'
dates.append(test)
dates.sort()
index = dates.index(test)
print dates[:index]
print dates[index + 1:]
输出
['11/09/2013', '12/09/2013', '20/09/2013']
['27/09/2013', '30/09/2013']
您可以获得所需的结果。