HiveBrain v1.2.0
Get Started
← Back to all entries
snippetpythonTip

Date is weekend or weekday

Submitted by: @import:30-seconds-of-code··
0
Viewed 0 times
weekdaypythondateweekend

Problem

To check if the given date is a weekend, you can use datetime.datetime.weekday() to get the day of the week as an integer. Then, you can check if the day of the week is greater than 4.
For the opposite case (checking if the date is a weekday), you can use the same technique, but checking if the day of the week is less than or equal to 4.

Solution

from datetime import datetime, date

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

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

Code Snippets

from datetime import datetime, date

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

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

def is_weekday(d = datetime.today()):
  return d.weekday() <= 4

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

Context

From 30-seconds-of-code: is-weekend-or-weekday

Revisions (0)

No revisions yet.