2017-07-18 78 views
0

所以我有8日期對象的列表看起來像這樣:如何檢查python中的日期字符串的日期?

0. June 01, 2017 
1. June 23, 2017 
2. June 13, 2017 
3. June 27, 2017 
4. June 17, 2017 
5. June 04, 2017 
6. June 09, 2017 
7. June 11, 2017 
8. June 15, 2017 

鑑於上述數據,我如何(在date_list每個日期),檢查日期是週末(星期六|太陽)還是不?根據答案,我會在if塊被分配變量:

if (date != weekend){ 
    weekdayCode(); 
} else { 
    weekendCode(); 
} 
+0

這是一個python的'list'或者它是文本中的文本嗎?日期字符串或'datetime.datetime'對象? – mgilson

+0

它確實是一個'list'!日期本身是'字符串' – tushariyer

回答

1

解析它的日期時間和呼叫weekday()

import datetime 

for date_string in list_of_strings:  
    dt = datetime.datetime.strptime(date_string, '%B %d, %Y') 
    if dt.weekday() in (5, 6): 
     print('{} is on a weekend'.format(date_string)) 
    else: 
     print('{} is a weekday'.format(datestring)) 
+0

該代碼只能使用提供的日期時間格式。只是想要爲任何計劃以現有形式使用它的人提供幫助。 – BoboDarph

+0

不錯的答案,我相信元組應該是(0,6) – redFur

+1

哦,不,你是對的我的壞! :)奇怪的是'weekday()'在週末時返回(5,6),但是當用'strptime'解析時,週末是(0,6) – redFur