Explain Codes LogoExplain Codes Logo

How do I get the day of week given a date?

python
datetime
strftime
locale
Nikita BarsukovbyNikita Barsukov·Nov 1, 2024
TLDR

Utilize Python's datetime module and its strftime('%A') method to extract the day name or weekday() method for the day index (Monday=0). Here is an illustration:

from datetime import datetime # Grabbing day name day_name = datetime.strptime('2023-04-21', '%Y-%m-%d').strftime('%A') # 'Friday' # Snatching day index day_index = datetime.strptime('2023-04-21', '%Y-%m-%d').weekday() # 4

Dabbling with weekdays in Python is a breeze, thanks to datetime. Be it names or indices of days, Python has it all under control.

The art and science of weekday()

The datetime.weekday() function promptly serves you the day as an integer. Remember:

  • Monday is 0
  • Sunday is 6
# "Is it a bird? Is it a plane? No, it's the weekday function!" print(datetime(2023, 4, 21).weekday()) # Output: 4 (Friday)

The date.isoweekday() bends the rules a bit, switching to ISO standards where Monday is 1:

from datetime import date # "In a world, where Monday gets the first place..." print(date(2023, 4, 21).isoweekday()) # Output: 5 (Friday)

strftime(): Your gateway to weekday names

If you're after the day's name, strftime has your back with its "%A" format specifier for the full name, and "%a" for the abbreviated form:

# "And on Fridays, we print 'Friday'"! print(datetime(2023, 4, 21).strftime('%A')) # Output: 'Friday' # "'Fri' for Friday, 'cause who needs extra characters!" print(datetime(2023, 4, 21).strftime('%a')) # Output: 'Fri'

Tending to contemporary cases

For UIs or locales, apply the locale module to fetch the weekday name in the user's language:

import locale from datetime import datetime locale.setlocale(locale.LC_TIME, '') # "Localizing the day, because we respect diversity!" localized_day = datetime.now().strftime('%A') # e.g., 'Freitag' in German locale print(localized_day)

Avoiding a date with disaster

Always be ready to parse strings cautiously using strptime or absorb errors gracefully:

from datetime import datetime # "Let's face it, not every input is a perfect date!" try: user_date = datetime.strptime(input("Enter a date (yyyy-mm-dd): "), '%Y-%m-%d') print(user_date.strftime('%A')) except ValueError: print("That's not a valid date format. Try again.")

Embracing special cases and tricks

Occasionally, you'll grapple with non-standard date formats or need to forecast the weekday in the future or past. Here's how:

# "Custom format? Bring it on!" custom_date = datetime.strptime('21.04.2023', '%d.%m.%Y').strftime('%A') # 'Friday' # "Predicting the weekday of the future. Call me Pythonstradamus!" days_to_add = datetime.timedelta(days=10) future_date = datetime.now() + days_to_add future_weekday = future_date.strftime('%A') # Day name 10 days from now

Dancing with the calendar module

Fancy a complete week view? Pair Python's calendar module with datetime. Harness the full weekday names:

import calendar # "Why choose one when you can have them all?" weekdays = list(calendar.day_name) # Access full weekday names selected_day = weekdays[datetime.now().weekday()] # Current day full name

Tips for efficiency

In time-sensitive applications, optimization rules. Leverage built-in methods effectively, but entertain caching for recurrent computations:

from functools import lru_cache # "Cache money, y'all!" @lru_cache(maxsize=None) def get_weekday_name(date_string): return datetime.strptime(date_string, '%Y-%m-%d').strftime('%A') # Check the cached function print(get_weekday_name('2023-04-21')) # 'Funday! I mean, Friday!'

Thanks to @lru_cache, Python remembers the result, eliminating the processing time for future repeats.