python-time和datetime

https://docs.python.org/3/library/time.html#module-time 

time.time()

import time
print(time.time())

#浮点数,称为UNIX纪元时间戳,是从1970年1月1日0点起到今天经过的秒数。
#有6位小数,使用round函数,可以实现浮点数的四舍五入。
#可指定参数保留的小数位数print(round(time.time(), 2))

 time.sleep()

time.sleep(sec)可以让当前休眠,参数填入秒(s)。


time.gmtime()

UTC时间
print(time.gmtime())


time.localtime()

本地时间,中国UTC+8
print(time.localtime())


datetime

接受7个参数,分别对应年、月、日、时、分、秒、微秒。分别保存在datetime的year、month、day、hour、minute、second、microsecond属性中 

from datetime import datetime

# 返回当前时间
now = datetime.now()
print(now.year, now.month, now.microsecond)

# 可以自定义参数,返回格式化后的时间
dt = datetime(2018, 11, 4, 20, 22, 54, 156025)
print(dt)

时间戳 

使用时间戳可以方便地计时一段程序地运行时间

start_time = time.time()

do ........

end_time = time.time()
print(end_time - start_time)

使用clock
clock第一次调用时它返回的是进程运行的时间。之后再次调用都是与第一次调用clock的值的差。即从第一次调用开始算起,到当前调用clock所经历的时间。 

start = time.clock()
time.sleep(2)
end = time.clock()
print(end - start)  # 差值代表了中间代码运行时间
原文地址:https://www.cnblogs.com/onenoteone/p/12441776.html