1 问题
编写一个获取当前日期所属的周的所有日期信息,程序需要的模块是datetime日期模块calendar日历模块。
2 方法
- 用datetime和caendar模块
代码清单 1
# 导入日期和日历模块 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); |
---|
3 结语
对于我们获取当前日期的信息可以我们通过python的实现,增加更多内容我们可以变成日历查看更多的内容,看天气其他更多功能。