程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Python:獲取指定日期為星期幾

編輯:Python

簡介:星期,又叫周,是一個時間單位,也是制定工作日、休息日的依據。獲取指定時間是星期幾,主要通過datetime、calendar、pendulum,其中datetime、calendar均為內置模塊,可以直接導入;pendulum為第三方模塊,需要先安裝。

相關攻略:
Python:zhdate模塊農歷日期處理
Python:radar生成隨機的日期、時間

安裝:

pip install pendulum

案例源碼:

# -*- coding: utf-8 -*-
# time: 2022/6/9 14:07
# file: weekday_demo.py
# author: tom
# 公眾號: 玩轉測試開發
import calendar
import datetime
import pendulum
class Weekday(object):
@staticmethod
def method_one(year: int, moth: int, day: int):
""" # weekday_list = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"] weekday: 返回 0-6 之間的整數 :param year: :param moth: :param day: :return: """
return datetime.datetime(year, moth, day).weekday()
@staticmethod
def method_two(year: int, moth: int, day: int):
""" isoweekday: 返回 1-7 之間的整數 :param year: :param moth: :param day: :return: """
weekday_list = ["", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六", "星期日"]
return weekday_list[datetime.datetime(year, moth, day).isoweekday()]
@staticmethod
def method_three(year: int, moth: int, day: int):
""" strftime: 輸出日期的英文周名,參數: %A :param year: :param moth: :param day: :return: """
return datetime.datetime(year, moth, day).strftime("%A")
@staticmethod
def method_four(year: int, moth: int, day: int):
""" strftime: 輸出日期的英文周名簡寫,參數: %a :param year: :param moth: :param day: :return: """
return datetime.datetime(year, moth, day).strftime("%a")
@staticmethod
def method_five(year: int, moth: int, day: int):
""" weekday: 返回 0-6 之間的整數 :param year: :param moth: :param day: :return: """
return calendar.weekday(year, moth, day)
@staticmethod
def method_six(year: int, moth: int, day: int):
""" day_of_week: 返回 1-7 之間的整數 :param year: :param moth: :param day: :return: """
year, moth, day = str(year), str(moth), str(day)
if len(moth) == 1:
moth = "0" + moth
if len(day) == 1:
day = "0" + day
return pendulum.parse(f'{
year}-{
moth}-{
day}').day_of_week
if __name__ == '__main__':
# 以 2022-06-09 星期三 為例,
w = Weekday()
r1 = w.method_one(2022, 6, 9)
print(f"r1:{
r1}") # r1:3,即星期四
r2 = w.method_two(2022, 6, 9)
print(f"r2:{
r2}") # r2:星期四
r3 = w.method_three(2022, 6, 9)
print(f"r3:{
r3}") # r3:Thursday
r4 = w.method_four(2022, 6, 9)
print(f"r4:{
r4}") # r4:Thu
r5 = w.method_five(2022, 6, 9)
print(f"r5:{
r5}") # r5:3,即星期四
r6 = w.method_six(2022, 6, 9)
print(f"r6:{
r6}") # r6:4,即星期四

微信公眾號:玩轉測試開發
歡迎關注,共同進步,謝謝!


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved