datetime 模块下包含date、time、datetime、timedelta
1.date:构造日期
# date.today()直接获取今天的日期
# date(year= , month= , day= ,)构造指定的日期
# strftime 将时间格式化格式化
date0 = date(year=2001, month=1, day=10)
# 获取今天日期
date0 = date.today()
print(type(date0))
# 取得日期中每一个部分
print(date0.year, date0.month, date0.day, date0.weekday())
2.time: 构造时间
time0 = time(hour=17, minute=1, second=30)
print(type(time0))
print(time0.hour, time0.minute, time0.second)
print(time0.strftime("%H:%M:%S"))
# %H表示小时 %M表示分钟 %S表示秒
print(time.localtime())
print(time.strftime("%Y/%m/%d %H:%M:%S", time.localtime()))
# 获取本地时间的年、月、日、时、分、秒
3 datetime:构造时间日期
datetime0 = datetime(year=2001, month=5, day=25, hour=5, minute=29, second=11)
datetime0 = datetime.now()
print(type(datetime0))
print(datetime0.year, datetime0.month, datetime0.day, datetime0.hour, datetime0.minute, datetime0.second)
print(datetime0.strftime("%Y-%m-%d %H:%M:%S"))
# %Y是表示4位年 %y表示两位年 %m表示两位月 %d表示两位日
4 timedelta:时间增量
now = datetime.now()
print(now.strftime("%Y/%m/%d %H:%M:%S"))
timedelta0 = timedelta(weeks=1, days=1, hours=2, seconds=30)
print(timedelta0.days, timedelta0.seconds)
future = now + timedelta(weeks=2, hours=2)
print(type(future), future.strftime("%Y/%m/%d %H:%M:%S"))
future = now - timedelta(hours=8)
print(type(future), future.strftime("%Y/%m/%d %H:%M:%S"))
# future的时间日期是在现在的时间日期基础上加上时间增量
5.time:时间模块
# time sleep(几秒) 阻塞模块、等待秒数
# time.time 整数部分是从1970-1-1 0时到现在的秒数 以秒为单位的时间戳
# time.strftime("%Y/%m/%d %H:%M:%S",(1999,9,9,9,9,9,0,0,0))
import time
print(time)
print(1)
time.sleep(5)
print(2)
time.sleep(5)
print(3)
time.sleep(5)
# 打印数字1、2、3,间隔5秒再打印下一个数
print(time.time())
time.sleep(5)
print(time.time())
time.sleep(5)
print(time.time())
# time.time整数部分是从1970-1-1 0时到现在的秒数
6. calendar:日历
import calendar
print(calendar)
# 年历
print(calendar.calendar(2024))
# 月历
print(calendar.month(2024, 1))
# 周几
print(calendar.weekday(2024, 1, 11))
# 是否为闰年
print(calendar.isleap(2001))
# 这里的weekday是打印周几,这里的周几是0-6,从0开始