2015-12-16 70 views
0

指數假設我有日期的列表:分割清單上的價值

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

如果「測試」實際上屬於(包含)在列表中,就必須在列表1

我想everyth仍然沒有運氣。

+6

把它們全部變成日期時間對象,對它們進行排序/過濾? – dwanderson

+1

你已經試過**一切**你試過了什麼? – taesu

回答

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

如何將項目轉換爲日期時間對象?

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] 

這是我得到的輸出使用與您給出datestest值上面的代碼時:

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

你可以得到你想要的結果。

+1

按照字典順序排列日期/月/年的格式是危險的。它只在這裏工作,因爲所有的飛蛾和年份都是一樣的。 – DSM