简介:星期,又叫周,是一个时间单位,也是制定工作日、休息日的依据。获取指定时间是星期几,主要通过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,即星期四
微信公众号:玩转测试开发
欢迎关注,共同进步,谢谢!