30秒学会 Python 片段 · 2023年9月23日

30秒学会 Python 片段 – Date is weekend

Checks if the given date is a weekend.

  • Use datetime.datetime.weekday() to get the day of the week as an integer.
  • Check if the day of the week is greater than 4.
  • Omit the second argument, d, to use a default value of datetime.today().

代码实现

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

翻译自:https://www.30secondsofcode.org/python/s/is-weekend