作用:用于时间间隔计算
import time
print(time.time())
# 结果
1663483667.3648992
作用:用于展示时间
import time
print(time.strftime('%Y-%m-%d %H:%M:%S'))
print(time.strftime('%Y-%m-%d %H:%M:%S %p'))
print(time.strftime('%Y-%m-%d %X'))
# 结果
2022-09-18 14:50:28
2022-09-18 14:50:28 PM
2022-09-18 14:50:28
作用:用于单独获取时间的某一部分
import time
res=time.localtime()
print(res)
#获取当前年份
print(res.tm_year)
print(res.tm_yday)
import datetime
print(datetime.datetime.now())
# 结果
import datetime
print(datetime.datetime.now())
import datetime
print(datetime.datetime.now())
print(datetime.datetime.now() + datetime.timedelta(days=3))
print(datetime.datetime.now() + datetime.timedelta(days=-3))
print(datetime.datetime.now() - datetime.timedelta(days=3))
print(datetime.datetime.now() + datetime.timedelta(weeks=1))
# 结果
2022-09-18 15:03:56.597750
2022-09-21 15:03:56.597750
2022-09-15 15:03:56.597750
2022-09-15 15:03:56.597750
2022-09-25 15:03:56.597750
import time
s_time=time.localtime()
print(s_time)
print(time.mktime(s_time))
# 结果
time.struct_time(tm_year=2022, tm_mon=9, tm_mday=18, tm_hour=15, tm_min=8, tm_sec=16, tm_wday=6, tm_yday=261, tm_isdst=0)
1663484896.0
import time
tp_time=time.time()
print(tp_time)
# 显示当前时区结构化时间(东八区)
print(time.localtime(tp_time))
# 显示格林威治时间,世界标准时间
print(time.gmtime(tp_time))
# 结果
1663485317.0527556
time.struct_time(tm_year=2022, tm_mon=9, tm_mday=18, tm_hour=15, tm_min=15, tm_sec=17, tm_wday=6, tm_yday=261, tm_isdst=0)
time.struct_time(tm_year=2022, tm_mon=9, tm_mday=18, tm_hour=7, tm_min=15, tm_sec=17, tm_wday=6, tm_yday=261, tm_isdst=0)
import time
s_time=time.localtime()
print(s_time)
# 格式化字符串形式的时间《-- 结构化时间
res=time.strftime('%Y-%m-%d %X', s_time)
print(res)
# 格式化字符串形式的时间 --》结构化时间
print(time.strptime(res, '%Y-%m-%d %X'))
# 结果
time.struct_time(tm_year=2022, tm_mon=9, tm_mday=18, tm_hour=20, tm_min=36, tm_sec=18, tm_wday=6, tm_yday=261, tm_isdst=0)
2022-09-18 20:36:18
time.struct_time(tm_year=2022, tm_mon=9, tm_mday=18, tm_hour=20, tm_min=36, tm_sec=18, tm_wday=6, tm_yday=261, tm_isdst=-1)
import time
# format string --> struct_time --> timestamp
res = '2022-09-18 20:36:18'
struct_time = time.strptime(res, '%Y-%m-%d %X')
print(struct_time)
timestamp = time.mktime(struct_time)
print(timestamp)
# 七天后
timestamp_add_7_day = timestamp+7*86400
print(timestamp_add_7_day)
# format string <-- struct_time <-- timestamp
res = time.strftime('%Y-%m-%d %X', time.localtime(timestamp_add_7_day))
print(res)
# 结果
time.struct_time(tm_year=2022, tm_mon=9, tm_mday=18, tm_hour=20, tm_min=36, tm_sec=18, tm_wday=6, tm_yday=261, tm_isdst=-1)
1663504578.0
1664109378.0
2022-09-25 20:36:18
import time
print(time.time())
time.sleep(10)
print(time.time())
# 结果
1663505841.6191862
1663505851.6268256
import time
print(time.asctime())
# 结果
Sun Sep 18 20:59:58 2022
import datetime
print(datetime.datetime.now())
print(datetime.datetime.utcnow())
# 结果
2022-09-18 21:02:36.805656
2022-09-18 13:02:36.805656
import datetime
print(datetime.datetime.fromtimestamp(766666666))
# 结果
1994-04-18 18:57:46