Python中的时间模块
时间表示的几种形式
1.时间戳
2.字符串时间
3.元组类型的时间
1. 时间戳
time.time() 1970纪元后经过的浮点秒数
import time
import os
print(time.time())
输出结果:
1580413901.7969923
2. 字符串时间
time.ctime()
import time
import os
print(time.ctime())
输出结果:
Fri Jan 31 03:53:33 2020
3. 元组时间
time.localtime()
import time
import os
print(time.localtime())
info = time.localtime()
print(info)
print(info.tm_year)
print(info.tm_mon)
输出结果:
time.struct_time(tm_year=2020, tm_mon=1, tm_mday=31, tm_hour=3, tm_min=56, tm_sec=0, tm_wday=4, tm_yday=31, tm_isdst=0)
time.struct_time(tm_year=2020, tm_mon=1, tm_mday=31, tm_hour=3, tm_min=56, tm_sec=0, tm_wday=4, tm_yday=31, tm_isdst=0)
2020
1
4. 常用时间的转换
4.1 把元组时间转换为时间戳
time.mktime(tupletime)
import os
import time
tuple_time = time.localtime() # 元组时间
print(tuple_time)
print(time.mktime(tuple_time))
输出结果:
time.struct_time(tm_year=2020, tm_mon=1, tm_mday=31, tm_hour=4, tm_min=49, tm_sec=50, tm_wday=4, tm_yday=31, tm_isdst=0)
1580417390.0
4.2 把元组时间转化为字符串时间
time.strftime()
import os
import time
tuple_time = time.localtime()
print(tuple_time)
print(time.strftime('%d-%m',tuple_time))
print(time.strftime('%Y/%m/%d',tuple_time))
print(time.strftime('%T',tuple_time))
print(time.strftime('%F',tuple_time))
输出结果:
time.struct_time(tm_year=2020, tm_mon=1, tm_mday=31, tm_hour=4, tm_min=52, tm_sec=10, tm_wday=4, tm_yday=31, tm_isdst=0)
31-01
2020/01/31
04:52:10
2020-01-31
4.3 将时间戳类型的时间转换为字符串时间
os.path.getatime(path) 返回最近访问时间(浮点型秒数)
os.path.getmtime(path) 返回最近文件修改时间
os.path.getctime(path) 返回文件创建时间
import os
import time
pwd_time = os.path.getctime('/etc/passwd')
print(pwd_time)
print(time.ctime(pwd_time))
输出结果:
1571910623.3680317
Thu Oct 24 17:50:23 2019
4.4 将时间戳类型转换为元组类型的时间
import os
import time
pwd_time = os.path.getctime('/etc/passwd')
print(time.localtime(pwd_time))
输出结果:
time.struct_time(tm_year=2019, tm_mon=10, tm_mday=24, tm_hour=17, tm_min=50, tm_sec=23, tm_wday=3, tm_yday=297, tm_isdst=0)
4.5 将元组时间转化为时间戳
import os
import time
tuple_time = time.localtime()
print(time.mktime(tuple_time))
输出结果:
1580418266.0