判断日期是否为周末

Beginner

This tutorial is from open-source community. Access the source code

简介

在 Python 中,datetime 模块提供了用于处理日期和时间的类。一个常见的任务是检查给定日期是否为周末。在这个挑战中,你将编写一个函数,该函数以日期作为输入,如果是周末则返回 True,否则返回 False

判断日期是否为周末

编写一个函数 is_weekend(d),该函数接受一个日期对象作为输入,如果给定日期是周末,则返回 True,否则返回 False。如果未提供参数,该函数应使用当前日期。

要解决此问题,你可以按以下步骤操作:

  1. 使用 datetime.datetime.weekday() 方法获取星期几的整数值。
  2. 检查星期几是否大于 4。如果是,则返回 True,否则返回 False
from datetime import datetime

def is_weekend(d = datetime.today()):
  return d.weekday() > 4
from datetime import date

is_weekend(date(2020, 10, 25)) ## True
is_weekend(date(2020, 10, 28)) ## False

总结

在这个挑战中,你已经学会了如何编写一个 Python 函数来检查给定日期是否为周末。你使用了 datetime 模块来获取星期几的整数值,并检查它是否大于 4 来确定该日期是否为周末。