Hướng dẫn weekday name in python

Python’s DateTime module offers a wide range of time-handling functions that make life a breeze. However, there’s no direct method to return a plain-English representation of a weekday name. Fortunately, there are several easy ways to get there.

Before we take a look at getting the weekday name, let’s consider how Python’s datetime class gets a date and, subsequently, determines the day of the week for said date. There’s nothing fancy about it—but it pays to know where you’re starting.

from datetime import datetime

# Create datetime object
date = datetime.now()
>>> 2021-02-07 15:30:46.665318

# Get the weekday value, as an integer
date.weekday()
>>> 6

This code illustrates how far the datetime class will get you before you have to start getting creative.  Before we move on, there are two things worth noting:

  • The weekday method assigns Monday the value 0
  • Another method, the isoweekday, assigns Sunday the value of 1

Check out the official datetime.weekday documentation for more info. Now, knowing how to get an integer representation of the weekday for a given datetime object, we can start scheming on how to produce a plain-English version. Below are three approaches ranked in order of dependencies.

Method 1: Do it Manually

# Define a list of weekday names
days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']

# Index using weekday int value
days[date.weekday()]

>>> Sunday

This approach offers the flexibility of being able to tweak weekday naming and order on-the-fly. Need to truncate the date names? Just edit the list. Need to start with Sunday? Just re-arrange it. Need to reverse the list for some strange reason? Just reverse it!

Pros:

  • No added dependencies
  • No added methods to remember
  • Flexibility for change
  • Explicit representation in code

Cons:

  • More typing
  • Not immediately resistant to duplication issues (i.e. using it across a project)
  • The fear of typos

Method 2: Use Strftime

# Convert the integer to english representation
date.date().strftime("%A")

>>> Sunday

This method is, arguably, the most succinct. It’s a reasonable one-liner, doesn’t stray from the datetime class, and offers some flexibility once familiar with the strftime documentation.

Pros:

  • No extra dependencies
  • One-liner possible
  • Semi-flexible
  • No fear of typos
  • Easy to integrate project-wide

Cons:

  • Need to be familiar with strftime to change format

Method 3: The Calendar Module

import calendar

# Convert using calender's day_name method
calender.day_name[date.weekday()]

>>> Sunday

This is really just a round-about way to achieve the same result as the first method. The added benefit here is that someone else manages the weekday list (not really a burden in this case.) The calender.day_name object is just a fancy list of all weekday names. Indexing into this object is the same as indexing into a manual list.

Pros:

  • Built-in module
  • Lightweight dependency
  • Uses native Python syntax for indexing

Cons:

  • Extra dependency
  • The syntax could be simpler

Final Thoughts

When I was first learning to code, one of the biggest surprises to me was how complex managing time and dates can be. The subtle length differences in months, leap years, converting strings to datetimes—it seemed like wading into the deep end for what was such a peripheral task.

Converting computer-friendly date representations like epoch timestamps into user-friendly representations is another annoyingly demanding task. In this case, Python’s datetime class makes it simple to get the weekday integer. After that, it’s all just syntactic sugar! Personally, I prefer method two here because it keeps everything tightly coupled to the DateTime module.

The reason your code is only returning one day name is because weekday will never match more than one string in the days tuple and therefore won't add any of the days of the week that follow it (nor wrap around to those before it). Even if it did somehow, it would still return them all as one long string because you're initializing result to an empty string, not an empty list.

Nội dung chính

  • How do I display weekdays in Python?
  • How do I get next weekday in Python?
  • How do I check if today is Monday in Python?
  • What weekday is 1 in Python?

Here's a solution that uses the datetime module to create a list of all the weekday names starting with "Monday" in the current locale's language. This list is then used to create another list of names in the desired order which is returned. It does the ordering by finding the index of designated day in the original list and then splicing together two slices of it relative to that index to form the result. As an optimization it also caches the locale's day names so if it's ever called again with the same current locale (a likely scenario), it won't need to recreate this private list.

import datetime
import locale

def weekdays(weekday):
    current_locale = locale.getlocale()
    if current_locale not in weekdays._days_cache:
        # Add day names from a reference date, Monday 2001-Jan-1 to cache.
        weekdays._days_cache[current_locale] = [
            datetime.date(2001, 1, i).strftime('%A') for i in range(1, 8)]
    days = weekdays._days_cache[current_locale]
    index = days.index(weekday)
    return days[index:] + days[:index]

weekdays._days_cache = {}  # initialize cache

print(weekdays('Wednesday'))
# ['Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday', 'Monday', 'Tuesday']

Besides not needing to hard-code days names in the function, another advantage to using the datetime module is that code utilizing it will automatically work in other languages. This can be illustrated by changing the locale and then calling the function with a day name in the corresponding language.

For example, although France is not my default locale, I can set it to be the current one for testing purposes as shown below. Note: According to this Capitalization of day names article, the names of the days of the week are not capitalized in French like they are in my default English locale, but that is taken into account automatically, too, which means the weekday name passed to it must be in the language of the current locale and is also case-sensitive. Of course you could modify the function to ignore the lettercase of the input argument, if desired.

# set or change locale
locale.setlocale(locale.LC_ALL, 'french_france')

print(weekdays('mercredi'))  # use French equivalent of 'Wednesday'
# ['mercredi', 'jeudi', 'vendredi', 'samedi', 'dimanche', 'lundi', 'mardi']

My last post was about creating a list of times to choose in an appointment-type app. In that app I also have a list of the days of the week.

day_names = [         
'Monday',
'Tuesday',
'Wednesday',
'Thursday',
'Friday',
'Saturday',
'Sunday',
]

And, as in my previous post, I wanted to generate this list programmatically. This is the snippet I came up with.

import calendar  day_names = list(calendar.day_name)

I use this snippet in a calendar app. Let’s try an example.

import calendar 
import datetime
day_names = list(calendar.day_name)day_of_week = datetime.date(2017, 10, 18).weekday()
day = day_names[day_of_week]
print(day)

The day_of_week variable is an integer 0–6. The integer is then used as an index to find the corresponding day name. The result is:

Wednesday  Process finished with exit code 0

I hope you enjoyed this article. This article is also available as a video on YouTube on my ZennDogg’s 2 Minute Snippet channel. Cheers!

corresponding to the day of the week.  Here is the mapping of integer values to the days of the week.

# import Python's datetime module

import datetime

# weekdays as a tuple

weekDays = ("Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday")

# Find out what day of the week is this year's Christmas

thisXMas    = datetime.date(2017,12,25)

thisXMasDay = thisXMas.weekday()

thisXMasDayAsString = weekDays[thisXMasDay]

print("This year's Christmas is on a {}".format(thisXMasDayAsString))

# Find out what day of the week next new year is

nextNewYear     = datetime.date(2018,1,1)

nextNewYearDay  = nextNewYear.weekday()

nextNewYearDayAsString = weekDays[nextNewYearDay]

print("Next new year is on a {}".format(nextNewYearDayAsString))

How do I display weekdays in Python?

isoweekday() to get a weekday of a given date in Python Use the isoweekday() method to get the day of the week as an integer, where Monday is 1 and Sunday is 7. i.e., To start from the weekday number from 1, we can use isoweekday() in place of weekday() . The output is 1, which is equivalent to Monday as Monday is 1.

How do I get next weekday in Python?

import time from datetime import date,timedelta dmy=time. strftime("%d-%m-%Y")# getting the current date if dmy. strftime("%w") in set([6,7]): # checking if its a weekend( Sat/Sun) , if so advancing dmy=time. strftime("%d-%m-%Y")+ timedelta(days=dmy.

How do I check if today is Monday in Python?

weekday() == 0: print("Yes, Today is Monday") else: print("Nope...") from datetime import datetime # If today is Monday (1 = Mon, 2 = Tue, 3 = Wen ...) if datetime. today(). isoweekday() == 1: print("Yes, Today is Monday") else: print("Nope...")

What weekday is 1 in Python?

weekday() Function Of Datetime. date Class In Python.