python3时间
1、介绍
time模块是python的内部模块。用于获取系统时间,格式化输出,将参数解析为时间等。
2、函数
(1)获取当前时间
print(time.time(), type(time.time()))
- 返回float类型,1670592065.0852547形式,单位为秒
(2)获取当前时间
print(time.time_ns(), type(time.time_ns()))
- 返回int类型,1670592289035206400形式 ,单位为纳秒。1秒=10^9纳秒
(3)休眠
time.sleep(5)
print(123)
- 休眠,线程暂停执行,单位秒
(4)strftime
- 格式化
%Y Year with century as a decimal number.
%m Month as a decimal number [01,12].
%d Day of the month as a decimal number [01,31].
%H Hour (24-hour clock) as a decimal number [00,23].
%M Minute as a decimal number [00,59].
%S Second as a decimal number [00,61].
%z Time zone offset from UTC.
%a Locale's abbreviated weekday name.
%A Locale's full weekday name.
%b Locale's abbreviated month name.
%B Locale's full month name.
%c Locale's appropriate date and time representation.
%I Hour (12-hour clock) as a decimal number [01,12].
%p Locale's equivalent of either AM or PM.
示例:
print(time.strftime("%Y%m%d"))#20221103
(5)基于float数值获取时间
t = time.time()
print(t, type(t))
t2 = time.localtime(t)
print(t2)
print(t2.tm_year)
print(time.strftime('%Y', t2))
"""
1682606149.9445274 <class 'float'>
time.struct_time(tm_year=2023, tm_mon=4, tm_mday=27, tm_hour=22, tm_min=35, tm_sec=49, tm_wday=3, tm_yday=117, tm_isdst=0)
2023
2023
"""
3、计算程序运行时间
(1)
t1 = time.time_ns()
for i in range(1000):
s = i
print(s)
time.sleep(0.001)
t2 = time.time_ns()
# 运行过程的时间,单位秒
print((t2-t1)/(10**9)) # 约16秒多
(2)
t1 = time.time()
for i in range(1000):
s = i
print(s)
time.sleep(0.001)
t2 = time.time()
# 运行过程的时间,单位秒
print(t2-t1) # 约16秒多,float类型