Super complete! 6 ways to get the "day of the week" for a date in Python!

e4770fcfad0ea90c41e339179bf1dae5.png

When performing data analysis in Python, it is also necessary to group and summarize by date, for example, to find the periodicity of sales.

Then before using Python for data statistics, an additional step is required: get the day of the week from the specified date. For example, February 22, 2022, also happens to be the 22nd Tuesday of the first month, so many people register for marriage on this day. This article takes 2022-02-22 as an example to demonstrate 6 methods for Python to get the "day of the week" for the specified date !

2443d8a4ae5e611d7a8f74d3e9379587.png

weekday()

datetimeThe module is a Python built-in library, no need for pip installation. In addition to displaying date and time, it can also perform date and time operations and formatting.

datetimeThe methods in the module weekday()can be used to retrieve the day of the week, and the result returns an integer between 0-6, which is used to represent "Monday" to "Sunday".

Enter the following command in the interactive environment:

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

output:

1

In the code, the datetimemodule first converts the date consisting of the year, month and day to a datetime date. Then weekday()the method gets "2022-02-22" this day is Tuesday.

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

Enter the following command in the interactive environment:

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

output:

'星期二'

The result is that it is directly Tuesday.

isoweekday()

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

Enter the following command in the interactive environment:

import datetime
datetime.date(2022, 2, 22).isoweekday()

output:

2

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

strftime()

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

Use strftime()methods to display datetime objects as strings. We are actually very familiar with converting the date format into a string format. For example strftime('%b-%m-%y %H:%M:%S'), just change the instruction %Ain it to get the date of the week.

Enter the following command in the interactive environment:

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

output:

'Tuesday'

If you change %A in the code to %a, the output is the abbreviation of the day of the week.

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

output:

'Tue'

calendar

The calendar module in Python is calendaralso a built-in library, which provides many methods for us to deal with the calendar. It is very convenient to use. We can use it to make calendars/weekly calendars and so on. Similarly, it also provides 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)

output:

1

This is exactly the same as the datetimemodule method of the first method above.weekday()

If you want to directly output the English week name of the date, the calendarcalendar module also has a method to do so.

import datetime
import calendar

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

output:

'Tuesday'

pendulum

The datetime module also has some limitations, such as dealing with time zone issues, etc. And the pendulummodule is this third-party open source library that can solve all the problems of the built-in datetime module.

https://pypi.org/project/pendulum/

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

output:

2

The result of the output is directly "week 2".

Pandas

Finally, finally, I want to say one of my most commonly used methods. Because Xiao Wu usually processes data in Pandas, the method in Pandas will definitely be given priority to generate the "week" column.

Series.dtCan be used to access the value of a sequence in a datetimelike form and return several properties. Series.dt.day_name()The 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

The output is shown below:

51042c3c4b0c0601338fb2d0dfd8e3a6.png
df["week_num1"] = df["date"].dt.dayofweek
df["week_num2"] = df["date"].dt.weekday
df["week_name"] = df["date"].dt.day_name()
df

The output is shown below:

46b326651b8df2f73a0acaee965f8b77.png

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

I hope my sharing is 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~

This concludes our article. If you like today's Python tutorial, please continue to follow us!


Interested students can quickly join our planet

3 weeks zero basic introduction provides 10 lessons

12 interesting practical projects throughout the year including source code,

Reward outstanding Top3 students every month to send books

Professional Q&A group, nanny-style teaching by Dachang teachers

If you are not satisfied, feel free to refund within three days! 88 a year, now 16 yuan off

3670dfec7d0fd244ca0b453196ddff5d.png

Scan the code to join, get started with zero basics in 3 weeks

推荐阅读:
入门: 最全的零基础学Python的问题  | 零基础学了8个月的Python  | 实战项目 |学Python就是这条捷径
干货:爬取豆瓣短评,电影《后来的我们》 | 38年NBA最佳球员分析 |   从万众期待到口碑扑街!唐探3令人失望  | 笑看新倚天屠龙记 | 灯谜答题王 |用Python做个海量小姐姐素描图 |碟中谍这么火,我用机器学习做个迷你推荐系统电影
趣味:弹球游戏  | 九宫格  | 漂亮的花 | 两百行Python《天天酷跑》游戏!
AI: 会做诗的机器人 | 给图片上色 | 预测收入 | 碟中谍这么火,我用机器学习做个迷你推荐系统电影
小工具: Pdf转Word,轻松搞定表格和水印! | 一键把html网页保存为pdf!|  再见PDF提取收费! | 用90行代码打造最强PDF转换器,word、PPT、excel、markdown、html一键转换 | 制作一款钉钉低价机票提示器! |60行代码做了一个语音壁纸切换器天天看小姐姐!|

The year's hottest copy

Click to read the original text to see 200 Python cases!

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326842103&siteId=291194637