Python编程获取当前日期的所属周日期信息
今天继续学习Python编程,偶然看到一篇博客关于日期的操作,于是参照一下编写了一个获取当前日期所属的周的所有日期信息。本人的环境是Pycharm+macOS,程序需要的模块是datetime日期模块calendar日历模块。源码如下:
#_*_coding:utf-8_*_
# 作者 :liuxiaowei
# 创建时间 :3/12/22 11:07 AM
# 文件 :一周内的日期显示.py
# IDE :PyCharm
# 导入日期和日历模块
import datetime
import calendar
# 定义一个字典存储星期几和对应的索引
weekDict = {
'0':'Monday', '1': 'Tuesday', '2': 'Wednesday', '3':'Thursday', '4': 'Friday', '5': 'Saturday', '6': 'Sunday'}
# 定义一个天数字典
dayDict = {
'1':'1st', '2':'2nd', '3':'3nd', '4':'4th', '5':'5th', '6':'6th','7':'7th'}
# 定义一个显示本周所有日期的函数
def show_currentweek_info():
# 获取当天的日期并赋值给weekday变量
weekday = datetime.date.today()
# 设定一个一天为基准的变量
one_day = datetime.timedelta(days=1)
# for 循环是为了显示当前的日期信息
for i in range(7):
# 判断当前日期对应的数字
if weekday.weekday() == i:
# 判断对应的日期是本周的第几天
day_number = datetime.date.isoweekday(weekday)
print(f'\nThe current date is:{weekday} Today is {weekDict[str(i)][:3]} It\'s the No.{dayDict[str(day_number)]} day of this week.\n')
# 判断周一到周日的日期
for i in range(7):
while weekday.weekday() != i:
# 判断当前日期在周一到周日之前还是之后,如果在周一-周日(包括周一,周日)之前那就一天一天加
if weekday.weekday() <= i:
weekday += one_day
day_number = datetime.date.isoweekday(weekday)
# 如果在周一-到周日之后(包括周一,周日)那就一天一天减
elif weekday.weekday() > i:
weekday -= one_day
day_number = datetime.date.isoweekday(weekday)
print(f'{weekday} is {weekDict[str(i)][:3]} It is the No.{dayDict[str(day_number)]} day of this week.')
if __name__ == "__main__":
show_currentweek_info()
# 获取当前日期的年份
year = datetime.date.today().year
# 获取当前日期的月份
month = datetime.date.today().month
# 获取当月的日历
cal = calendar.month(year, month);
print(f"\nHere is the calendar of this month:");
print(cal);
运行结果如下:
The current date is:2022-03-12 Today is Sat It's the No.6th day of this week.
2022-03-07 is Mon It is the No.1st day of this week.
2022-03-08 is Tue It is the No.2nd day of this week.
2022-03-09 is Wed It is the No.3nd day of this week.
2022-03-10 is Thu It is the No.4th day of this week.
2022-03-11 is Fri It is the No.5th day of this week.
2022-03-12 is Sat It is the No.6th day of this week.
2022-03-13 is Sun It is the No.7th day of this week.
Here is the calendar of this month:
March 2022
Mo Tu We Th Fr Sa Su
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30 31
Process finished with exit code 0
备 注