1、导入calendar,datetime的time 模块;
2、显示今天的日期 date.today();
3、显示日历图 calendar.calendar(2021)
import calendar from datetime import date mydate = date.today() print("今天的日期:", mydate) year_calendar = calendar.calendar(2021) print(f"{mydate.year}年的日历图:{year_calendar}\n")
import calendar from datetime import date mydate = date.today() print("今天的日期:", mydate) is_leap = calendar.isleap(mydate.year) print(is_leap) print_leap_str = "%s年是闰年" if is_leap else "%s年不是闰年\n" print(print_leap_str % mydate.year)
import calendar from datetime import date mydate = date.today() print("今天的日期:", mydate) month_calendar = calendar.month(mydate.year, mydate.month) # 显示月的日历图 print(f"{mydate.year}年-{mydate.month}月的日历图:\n{month_calendar}\n")
# 这个月有几天 weekday, days = calendar.monthrange(mydate.year, mydate.month) print(weekday) # 9月1日是星期二 print(days) print(f'{mydate.year}年-{mydate.month}月的第一天是一周的第{weekday}天\n') print(f'{mydate.year}年-{mydate.month}月共有{days}天\n')
# 月第一天 month_first_day = date(mydate.year, mydate.month, 1) print(f"当月第一天:{month_first_day}\n") # 月最后一天 month_last_day = date(mydate.year, mydate.month, days) print(f"当月最后一天:{month_last_day}\n")
from datetime import date, datetime from time import localtime,strftime date_today = date.today() print("当前日期:",date_today) time_today = datetime.today() print("当前时间:",time_today) time_local = localtime() #本地时间 print(time_local) # 转化为"年-月-日 时:分:秒"的格式 print("本地时间:",strftime("%Y-%m-%d %H:%M:%S", time_local))
导入 from time import localtime,strptime
可以逆转时间格式。
from datetime import date, datetime from time import localtime,strptime struct_time = strptime('2021-09-23 12:45:45', "%Y-%m-%d %H:%M:%S") print("逆转时间格式:",struct_time) # struct_time类型就是time中的一个类