python3时间

发布时间 2023-04-15 12:50:31作者: 挖洞404

1、介绍

time模块是python的内部模块。

2、函数

# 返回float类型,1670592065.0852547形式
# print(time.time())
# print(type(time.time()))

# 休眠,单位秒
# time.sleep(5)
# print(123)

# 返回int类型,1670592289035206400形式
# print(time.time_ns())
# print(type(time.time_ns()))

(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

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类型