参考:https://blog.csdn.net/you_are_my_dream/article/details/61616465
在Python中,与时间处理有关的模块就包括:time,datetime以及calendar。这篇文章,主要讲解time模块。
在开始之前,首先要说明这几点:
-
在Python中,通常有这几种方式来表示时间:1)时间戳 2)格式化的时间字符串 3)元组(struct_time)(共九个元素)。
-
时间戳(timestamp)的方式:通常来说,时间戳表示的是从1970年1月1日00:00:00开始按秒计算的偏移量。
-
元组(struct_time)方式:struct_time元组共有9个元素,返回struct_time的函数主要有gmtime(),localtime(),strptime()。下面列出这种方式元组中的几个元素:
image.png
常用的方法有:
time.time()
:返回当前时间的时间戳。
time.sleep(secs)
:线程推迟指定的时间运行。单位为秒。
time.ctime([secs])
:把一个时间戳转化为如下特定格式。默认把time.time()做为参数。
>>> time.ctime()
'Fri Oct 19 10:21:50 2018'
time.strftime(format[, t])
:把一个代表时间的元组或者struct_time(如由time.localtime()返回)转化为格式化的时间字符串。如果t未指定,默认传入time.localtime()。
>>> time.strftime("%Y-%m-%d %X", time.localtime())
'2011-05-05 16:37:06'
round( x [, n] )
:返回浮点数x的四舍五入值。
>>> t1 = time.time()
>>> t2 = time.time()
>>> t = t2- t1
>>> t
5.39501428604126
>>> round(t)
5
>>> round(t, 3)
5.395
>>>
网友评论