Table of Contents
weekday()
isoweekday()
strftime()
calendar
pendulum
Pandas
Home Backend Development Python Tutorial Super complete! Six ways to get the 'day of the week' for a certain date in Python!

Super complete! Six ways to get the 'day of the week' for a certain date in Python!

Apr 19, 2023 am 09:28 AM
python date Order

Super complete! Six ways to get the 'day of the week' for a certain date in Python!

When performing data analysis in Python, grouping and summarizing by date is also needed, for example, to find the periodic pattern of sales.

So before using Python for data statistics, you need to add an extra step: get the day of the week from the specified date. For example, February 22, 2022, happens to be the 22nd Tuesday of the first lunar month, so there are particularly many people registering for marriage on this day. This article takes 2022-02-22 as an example to demonstrate 6 ways to get the "day of the week" for a specified date in Python!

Super complete! Six ways to get the 'day of the week' for a certain date in Python!

weekday()

The datetime module is a Python built-in library. There is no need to install pip. In addition to displaying the date and time, it can also Perform date and time operations and formatting.

The method weekday() in the datetime module can be used to retrieve the day of the week. The result returns an integer between 0 and 6, representing "Monday" to "Sunday".

Enter the following command in the interactive environment:

from datetime import datetime
datetime.date(2022, 2, 22).weekday()
Copy after login

Output:

1
Copy after login
Copy after login

In the code, the datetime module will first convert the date consisting of year, month and day into datetime date. Then the weekday() method gets "2022-02-22" which day is Tuesday.

But according to our domestic habits, we cannot directly output 1. So we can first customize a list containing Chinese "days of the week", and then return a Chinese day of the week through indexing.

Enter the following command in the interactive environment:

week_list = ["星期一","星期二","星期三","星期四","星期五","星期六","星期日"]
week_list[datetime.date(2022, 2, 22).weekday()]
Copy after login

Output:

'星期二'
Copy after login

The result is Tuesday directly.

isoweekday()

isoweekday() method works similarly to the previous weekday() method. The biggest difference is that it returns an integer between 1-7 to represent "weekday". Monday" to "Sunday".

Enter the following command in the interactive environment:

import datetime
datetime.date(2022, 2, 22).isoweekday()
Copy after login

Output:

2
Copy after login
Copy after login

The output result this time is directly "week 2".

strftime()

If you want to directly output the English week name of the date, you might as well try the strftime() method.

The datetime object can be displayed as a string using the strftime() method. We are actually very familiar with converting date format into string format, such as strftime('%b-%m-%y %H:%M:%S'). Just change the command to %A to get The date is the day of the week.

Enter the following command in the interactive environment:

import datetime
datetime.date(2022, 2, 22).strftime("%A")
Copy after login

Output:

'Tuesday'
Copy after login
Copy after login

If you change %A in the code to %a, the day of the week will be output Abbreviation.

datetime.date(2022, 2, 22).strftime("%a")
Copy after login

Output:

'Tue'
Copy after login

calendar

The calendar module in Python is also a built-in library, which provides many methods for us to process calendars and is very convenient to use. We can use it to make calendar/weekly calendar and so on. Similarly, it also provides the weekday() and day_name() methods to query the day of the week for a specified date.

Enter the following command in the interactive environment:

import calendar
calendar.weekday(2022, 2, 22)
Copy after login

Output:

1
Copy after login
Copy after login

This is exactly the same as the weekday() method of the datetime module in the first method above.

If you want to directly output the English week name of the date, the calendar module also has a method to achieve this.

import datetime
import calendar
date_week = datetime.date(2022, 2, 22).weekday()
calendar.day_name[date_week]
Copy after login

Output:

'Tuesday'
Copy after login
Copy after login

pendulum

The datetime module also has some limitations, such as handling time zone issues and so on. The pendulum module is a third-party open source library that can solve all problems of the built-in datetime module.

​https://www.php.cn/link/ebc03fa648c2cd7da9d63b9ed835664e​

Of course, it also has a method to output the day of the week for the specified date.

Enter the following command in the interactive environment:

import pendulum
pendulum.parse('2022-02-22').day_of_week
Copy after login

Output:

2
Copy after login
Copy after login

The output result is directly "week 2".

Pandas

Finally, finally, I want to talk about one of my most commonly used methods. Because Xiaowu usually processes data in Pandas, the method in Pandas will definitely be given priority when generating the "week" column.

Series.dt can be used to access the values ​​of a series in datetimelike form and return several properties. The Series.dt.day_name() function returns the date name with the DateTimeIndex of the specified locale.

Enter the following command in the interactive environment:

import pandas as pd
from datetime import datetime
df = pd.DataFrame({
"name": ["张三", "李四", "朱五"],
"date": [datetime(2022, 2, 21), datetime(2022, 2, 22), datetime(2022, 2, 23)]})
df
Copy after login

The output is as shown below:

Super complete! Six ways to get the 'day of the week' for a certain date in Python!##

df["week_num1"] = df["date"].dt.dayofweek
df["week_num2"] = df["date"].dt.weekday
df["week_name"] = df["date"].dt.day_name()
df
Copy after login
The output is as shown below:

Super complete! Six ways to get the 'day of the week' for a certain date in Python!

In today’s article, we introduced a total of 6 methods to get the day of the week from a specified date.

I hope my sharing will be helpful to you. If you see the friends at the end of the article, please give a like in the lower right corner before leaving~

The above is the detailed content of Super complete! Six ways to get the 'day of the week' for a certain date in Python!. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

Choosing Between PHP and Python: A Guide Choosing Between PHP and Python: A Guide Apr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Python: A Deep Dive into Their History PHP and Python: A Deep Dive into Their History Apr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Python vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Can vs code run in Windows 8 Can vs code run in Windows 8 Apr 15, 2025 pm 07:24 PM

VS Code can run on Windows 8, but the experience may not be great. First make sure the system has been updated to the latest patch, then download the VS Code installation package that matches the system architecture and install it as prompted. After installation, be aware that some extensions may be incompatible with Windows 8 and need to look for alternative extensions or use newer Windows systems in a virtual machine. Install the necessary extensions to check whether they work properly. Although VS Code is feasible on Windows 8, it is recommended to upgrade to a newer Windows system for a better development experience and security.

How to run sublime code python How to run sublime code python Apr 16, 2025 am 08:48 AM

To run Python code in Sublime Text, you need to install the Python plug-in first, then create a .py file and write the code, and finally press Ctrl B to run the code, and the output will be displayed in the console.

Can visual studio code be used in python Can visual studio code be used in python Apr 15, 2025 pm 08:18 PM

VS Code can be used to write Python and provides many features that make it an ideal tool for developing Python applications. It allows users to: install Python extensions to get functions such as code completion, syntax highlighting, and debugging. Use the debugger to track code step by step, find and fix errors. Integrate Git for version control. Use code formatting tools to maintain code consistency. Use the Linting tool to spot potential problems ahead of time.

Where to write code in vscode Where to write code in vscode Apr 15, 2025 pm 09:54 PM

Writing code in Visual Studio Code (VSCode) is simple and easy to use. Just install VSCode, create a project, select a language, create a file, write code, save and run it. The advantages of VSCode include cross-platform, free and open source, powerful features, rich extensions, and lightweight and fast.

See all articles