第8章 模块
8.2 常用模块
拓展:calendar
模块、datetime
模块、time
模块
# 年的日历图
import calendar
year = int(input('输入年份:'))
year_calendar_str = calendar.calendar(year)
print(f"{year}年的日历图:
{year_calendar_str}
")
# 月的日历图
import calendar
mydate = calendar
yy = int(input('输入年份:'))
mm = int(input('输入月份:'))
month_calendar_str = mydate.month(yy, mm)
print(f"{yy}年{mm}月的日历图:
{month_calendar_str}
")
# 月有几天
date = input("请输入4位数年-2位数月-2位数日:")
s = date.split('-')
year = int(s[0])
month = int(s[1])
day = int(s[2])
days = 0
if month in (1, 3, 5, 7, 8, 10, 12):
days = 31
elif month in (4, 6, 9, 11):
days = 30
elif month == 2:
if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):
days = 29
else:
days = 28
else:
print("月份输入出错啦!")
print(date + '当月天数为' + str(days))
# 根据年月日计算这是一年的第几天
"""
获取年、月、日.
计算这是这一年的第几天.
算法:前几个月的总天数 + 当月天数
比如2020,6,29
31 28 31 30 + 18
"""
year = int(input("请输入年:"))
month = int(input("请输入月:"))
day = int(input("请输入天:"))
day_of_February = 29 if year % 4 == 0 and year % 100 != 0 or year % 400 == 0 else 28
days_of_month = (31, day_of_February, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31)
# 累加前几个月的总天数
# total_days = 0
# for i in range( month -1 ):# 0 1 2 3
# total_days += days_of_month[i]
total_days = sum(days_of_month[: month - 1])
# 累加当月天数
total_days += day
print("这是一年的第"+str(total_days)+"天")
# 获取当前时间
from datetime import date, datetime
import time
today_date = date.today()
print(today_date) # 2019-12-22
today_time = datetime.today()
print(today_time) # 2019-12-22 18:02:33.398894
# 时间转字符时间
import time
local_time = time.localtime()
print(time.strftime("%Y-%m-%d %H:%M:%S", local_time)) # 转化为定制的格式 2019-12-22 18:13:41
# 判断是否为闰年
import calendar
year = int(input("请输入4位数的年份:"))
is_leap = calendar.isleap(year)
print_leap_str = "%s年是闰年" if is_leap else "%s年不是闰年
"
print(print_leap_str % year)