视频链接:https://www.bilibili.com/video/BV1SE411N7Hi?p=77
详细内容:https://guobaoyuan.gitee.io/new_book/Python/16-5%20time.html
#!/usr/bin/env python
# -*- coding:utf-8 -*-
import time
#time.sleep(2)#睡眠2秒
time.time()#时间戳 浮点型
'''
time分类:
1.时间戳-给程序员做计算 time.time()
2.结构化时间-给程序员 time.localtime()#无参数,默认当前时间戳
3.字符串时间-给用户看
时间戳和字符串时间,只能通过结构化时间进行转化
time.time()#时间戳
time.sleep()#睡眠
time.localtime()#将时间戳转换成结构化时间
time.strftime()#将结构化时间转化成字符串时间
time.strptime()#将字符串时间转换成结构化时间
time.mktime()#将结构化时间转成时间戳
'''
#将时间戳转换成字符串
print(time.time())#时间戳
print(time.localtime()) #无参数,默认当前时间戳,即time.localtime(time.time())
#元组 time.struct_time(tm_year=2020, tm_mon=7, tm_mday=10, tm_hour=11, tm_min=24, tm_sec=16, tm_wday=4, tm_yday=192, tm_isdst=0)
t=time.localtime(time.time())#结构化时间
print(t[0])#结构化时间是元组,可以用下标来取值
print(t.tm_mday)
t1=time.strftime("%Y-%m-%d %H:%M:%S",t)#字符串时间
#将字符串时间转换成时间戳
str_time='2019-12-13 11:07:06'
t_time=time.strptime(str_time,'%Y-%m-%d %H:%M:%S')
print(t_time)
print(time.mktime(t_time))#得到时间戳1576206426.0
'''
datetime是封装了time,在time的基础上增加了新的功能
'''
from datetime import datetime,timedelta#第一个datetime是文件夹,第二个datetime是模块
print(datetime.now())#2020-07-13 15:53:53.631970 获取当前时间
print(datetime(2019,10,1,12,13,14))#2019-10-01 12:13:14
str_time='2019-12-13 11:07:06'
print(datetime.strptime(str_time,'%Y-%m-%d %H:%M:%S'))#将字符串时间转成时间对象
import time
t=time.time()
print(datetime.fromtimestamp(t)-datetime(2018,11,8))#614 days, 16:04:20.514076
print(datetime.now())#拿到当前时间 2020-07-14 16:04:20.514075
print(datetime.strftime(datetime.now(),"%Y-%m-%d %H:%M:%S"))#时间对象转字符串 2020-07-14 16:06:01
print(datetime.timestamp(datetime.now()))#时间对象转换成时间戳
print(datetime.now()-timedelta(days=1))#2020-07-13 16:11:15.488409
print(datetime.now()-timedelta(days=365*2))#2018-07-15 16:12:09.316109
print(datetime.now()+timedelta(days=365*2))#2022-07-14 16:13:44.915456