1. time模块
time模块中时间表现的格式主要有三种:
a、timestamp时间戳,时间戳表示的是从1970年1月1日00:00:00开始按秒计算的偏移量
b、struct_time时间元组,共有九个元素组。
c、format time 格式化时间,已格式化的结构使时间更具可读性。包括自定义格式和固定格式。
import time
print(time.time()) # 生成timestamp
t = time.localtime() # struct_time时间元组,共有九个元素组
t = time.localtime(time.time()) # timestamp转化成struct_time
t = time.mktime(time.localtime()) # struct_time to timestamp
t = time.gmtime() # 格林威治时间
t = time.gmtime(time.time())
# format_time to struct_time
t = time.strptime('2011-05-05 16:37:06', '%Y-%m-%d %X')
# 生成format_time
t = time.strftime("%Y-%m-%d %X", time.localtime())
# 生成固定格式的时间表示格式
t = time.asctime(time.localtime())
t = time.ctime(time.time())
t = time.strftime("%Y-%m-%d %X") # 系统当前年月日及时间, %X 本地相应时间
# 时间加减, timestamp加减单位以秒为单位
t = time.time()
t = t + 100
t = time.ctime(t)
print(t)
2. calendar模块
import calendar
cal = calendar.month(2021, 12)
print(cal)
cal = calendar.calendar(2021)
cal = calendar.firstweekday() # 0 星期天
print(cal)
calendar.setfirstweekday(1)
print(calendar.firstweekday())
print(calendar.weekday(2021, 12, 16)) # 3表示周四
print(calendar.isleap(2020)) #是否闰年
print(calendar.leapdays(1000, 2020)) # 两年之间的闰年总数
# calendar.monthrange返回两个整数,第一个为该月的首日的星期(0-6),第二个为该月的总天数
print(calendar.monthrange(2020, 10))
3.datetime 模块
datetime模块提供用于处理日期和时间的类。主要有date类,time类 datetime类以及timedelta类等。
import datetime
## date类
a = datetime.date(2020, 12, 16)
a = datetime.date.today()
print(a.year, a.month, a.day)
# 符合ISO标准的日期格式 三个值依次为:year年份,week number周数,weekday星期数(周一为1…周日为7)
print(a.isocalendar())
print(a.isoformat()) # YYYY-MM-DD 格式
print(a)
print(a.isoweekday()) #返回符合ISO标准的指定日期所在的星期数(周一为1…周日为7)
print("time class...")
## time类
# time类由hour小时、minute分钟、second秒、microsecond毫秒和tzinfo五部分组成
a = datetime.time(10, 10, 49, 888)
print(a.strftime('%H:%M:%S')) # 格式化输出
print(a.isoformat()) # ISO标准格式
print(a)
## datetime类
a = datetime.datetime.now()
print(a)
# 格式化输出
print(a.strftime('%Y-%m-%d'))
print(a.strftime('%Y%m%d'))
print(a.strftime('%Y-%m'))
start_time = datetime.datetime.now()
end_time = datetime.datetime.now()
print((end_time - start_time).seconds)
## timedelta类: 用来计算二个datetime对象的差值
print(datetime.timedelta(days=7))
d1 = datetime.datetime.now()
d2 = d1 + datetime.timedelta(days=3, hours=8, minutes=3, seconds=2, microseconds=21)
print(d2)
print(datetime.time()) # 00:00:00
print(datetime.date.today()) # 当前日期
print(datetime.datetime.now()) # 当前日期时间