time
模块
time 模块,也就是时间模块,用来进行一些与时间有关的操作。其使用方法为:
1 2 3
| import time print(time.time()) print(time.sleep(2))
|
时间分类:
- 时间戳 — 用于进行计算
- 结构化时间 — 给程序员查看使用(命名元组)
- 字符串时间 — 给用户查看的
时间模块的基本方法有:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| 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)
|
输出的结果为:
1 2 3 4 5 6 7 8 9
| time.struct_time(tm_year=2019, tm_mon=9, tm_mday=26, tm_hour=19, tm_min=19, tm_sec=21, tm_wday=3, tm_yday=269, tm_isdst=0) 1569496761.0 2019-09-26 19:19:21 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) 2019-09-26 19:19:21 1567311786.0 2019 2019 269
|
datetime
模块
datetime 模块的作用和 time 模块类似,都是用来进行时间操作的,其基本操作为:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| 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))
|
输出的结果为:
1 2 3 4 5 6 7 8 9 10 11
| 2019-09-26 19:32:59.456316 <class 'datetime.datetime'> 2016-11-13 12:13:14 2019-09-26 19:32:59.457314 1569497579.457313 2019-09-26 19:32:59 2019-10-14 00:00:00 -2914671 days, 7:19:45.490226 2019-09-26 19:32:59.490226 2018-08-22 19:32:59.490226 2018-05-14 19:32:59.490226
|