如何在python中检查日期字符串的日期?

2024-09-19 23:39:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个8个日期对象的列表,如下所示:

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中的每个日期)检查该日期是否是周末(sat | sun)?根据答案,我将在if块中分配变量:

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

Tags: 数据对象答案列表dateifsatelse
1条回答
网友
1楼 · 发布于 2024-09-19 23:39:28

将其解析为datetime并调用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))

相关问题 更多 >