time 模块
time 模块,也就是时间模块,用来进行一些与时间有关的操作。其使用方法为:
import time
print(time.time())
print(time.sleep(2))
时间分类:
- 时间戳 — 用于进行计算
- 结构化时间 — 给程序员查看使用(命名元组)
- 字符串时间 — 给用户查看的
时间模块的基本方法有:
t = time.time()
print(time.localtime(t))
t = time.localtime()
print(time.mktime(t))
t = time.localtime()
print(time.strftime("%Y-%m-%d %H:%M:%S",t))
str_time = "2019-9-1 12:23:06"
print(time.strptime(str_time,"%Y-%m-%d %H:%M:%S"))
print(time.strftime("%Y-%m-%d %H:%M:%S",time.localtime()))
str_time = "2019-9-1 12:23:06"
print(time.mktime(time.strptime(str_time,"%Y-%m-%d %H:%M:%S")))
print(time.localtime()[0])
print(time.localtime().tm_year)
print(time.localtime().tm_yday)
输出的结果为:
time.struct_time(tm_year=2022, tm_mon=3, tm_mday=30, tm_hour=16, tm_min=43, tm_sec=52, tm_wday=2, tm_yday=89, tm_isdst=0)
1648629832.0
2022-03-30 16:43:52
time.struct_time(tm_year=2019, tm_mon=9, tm_mday=1, tm_hour=12, tm_min=23, tm_sec=6, tm_wday=6, tm_yday=244, tm_isdst=-1)
2022-03-30 16:43:52
1567311786.0
2022
2022
89
datetime 模块
datetime 模块的作用和 time 模块类似,都是用来进行时间操作的,其基本操作为:
'''
学习中遇到问题没人解答?小编创建了一个Python学习交流QQ群:857662006
寻找有志同道合的小伙伴,互帮互助,群里还有不错的视频学习教程和PDF电子书!
'''
from datetime import datetime
print(datetime.now())
print(type(datetime.now()))
print(datetime(2016, 11, 13, 12, 13, 14))
import time
print(datetime.fromtimestamp(time.time()))
print(datetime.timestamp(datetime.now()))
print(datetime.strftime(datetime.now(),"%Y-%m-%d %H:%M:%S"))
print(datetime.strptime("2019/10/14","%Y/%m/%d"))
print(datetime.now() - datetime(9999,11,1,12,13,14))
from datetime import datetime,timedelta
print(datetime.now())
print(datetime.now() - timedelta(days=400))
print(datetime.now() - timedelta(days=500))
输出的结果为:
2022-03-30 16:44:38.312694
<class 'datetime.datetime'>
2016-11-13 12:13:14
2022-03-30 16:44:38.312695
1648629878.312694
2022-03-30 16:44:38
2019-10-14 00:00:00
-2913755 days, 4:31:24.317681
2022-03-30 16:44:38.317681
2021-02-23 16:44:38.317681
2020-11-15 16:44:38.317681
|