Python 时间库 之 标准模块time

时间:2022-01-09 22:33:31

Python中的时间库有很多,特别推荐的有:六款Python 时间&日期库推荐

在学习Python的时间库时,应最先学习Python标准库中的模块:Time、Calendar、datetime、pytz、dateutil。打好基础后,再学习第三方库。本篇为Python时间库中的第一篇。

其他模块见:


一 time 模块

time模块的官方英文文档:time - time access and convertions

time模块的官方英文文档:time - 时间访问和转换

下面按照,从基础概念到常用函数的顺序介绍time模块

1 时间戳:格林威治时间1970年01月01日00分00秒(北京时间1970年01月01日08时00分00秒)起至现在的总秒数。

Python中获取时间的常用方法是,先得到时间戳,再将其转换成想要的时间格式

2 元组struct_time:日期、时间是包含许多变量的,所以在Python中定义了一个元组struct_time将所有这些变量组合在一起,包括:4位数年、月、日、小时、分钟、秒等。

所有变量及要求如下:

序号 字段
0 4位数年 2008
1 1 到 12
2 1到31
3 小时 0到23
4 分钟 0到59
5 0到61 (60或61 是闰秒)
6 一周的第几日 0到6 (0是周一)
7 一年的第几日 1到366 (儒略历)
8 夏令时 -1, 0, 1, -1是决定是否为夏令时的旗帜
对应的,struct_time元组的属性如下:

序号 属性
0 tm_year 2008
1 tm_mon 1 到 12
2 tm_mday 1 到 31
3 tm_hour 0 到 23
4 tm_min 0 到 59
5 tm_sec 0 到 61 (60或61 是闰秒)
6 tm_wday 0到6 (0是周一)
7 tm_yday 1 到 366(儒略历)
8 tm_isdst -1, 0, 1, -1是决定是否为夏令时的旗帜

3 Time 模块的常用内置函数

下述函数,按照官方文档中的顺序(按字母排序)选择性给出,若想查看全部函数,请转至Python官网。

3.1 time.asctime([t])

官方描述:

Convert a tuple or struct_time representing a time as returned by gmtime() or localtime() to a string of the following form: 'Sun Jun 20 23:21:051993'. If t is not provided, the current time as returned by localtime() is used. Locale information is not used by asctime().

Note

 

Unlike the C function of the same name, asctime() does not add a trailing newline.


译文:
gmtime()或localtime() 返回的 表示时间的 元组或struct_time 转换成一个字符串,格式:'Sun Jun 20 23:21:051993'。如果没有传入参数t,则使用localtime()返回的时间作为t。asctime()不使用时区信息。

注意   (1)与同名的C函数不同,asctime()不会在输出的末尾添加一个换行符。
         (2)这里的元组,指9个元素的元组,即与struct_time 相同格式的元组。


程序示例:

首先,使用函数gmtime()、localtime()的返回值作为参数。

>>> import time
>>> time.asctime(time.time()) #提供一个反例:time()函数返回时间戳,不能作为asctime()的参数,注意错误提示。
Traceback (most recent call last):
  File "<pyshell#7>", line 1, in <module>
    time.asctime(time.time())
TypeError: Tuple or struct_time argument required # 参数只能是元组或struct_time
>>> time.asctime(time.gmtime())
'Wed Jan 10 01:03:23 2018'
>>> time.asctime(time.localtime())
'Wed Jan 10 09:03:50 2018'
然后,自定义一个9个元素的元组作为参数。为了方便检查,我们首先使用gmtime()返回一个正确的时间元组,然后将各属性值拷贝到自定义元组中:

>>> time.gmtime()
time.struct_time(tm_year=2018, tm_mon=1, tm_mday=10, tm_hour=1, tm_min=11, tm_sec=24, tm_wday=2, tm_yday=10, tm_isdst=0)
>>> tuple_time = (2018,1,10,1,11,24,2,10,0) #9个元素的元组
>>> time.asctime(tuple_time)
'Wed Jan 10 01:11:24 2018'
>>> tuple_time = (2018,10,1,1,11,24,2,10,0) #若改变元组中元素的顺序,time.asctime()将不能正确表示时间。
>>> time.asctime(tuple_time)
'Wed Oct  1 01:11:24 2018'
>>> tuple_time = (2018,10,1,1,11,24,2,10) #若元组中元素个数不等于9个,将会报错
>>> time.asctime(tuple_time)
Traceback (most recent call last):
  File "<pyshell#17>", line 1, in <module>
    time.asctime(tuple_time)
TypeError: function takes exactly 9 arguments (8 given) #这里的参数提示有点歧义,应该是函数asctime()需要一个参数, 
#该参数中含有9个元素
>>> time.asctime(2018,10,1,1,11,24,2,10,0) #尝试错误提示中的函数需要9个参数,此时又报错。说明上面错误提示有歧义。 Traceback (most recent call last):
  File "<pyshell#19>", line 1, in <module>
    time.asctime(2018,10,1,1,11,24,2,10,0)
TypeError: asctime expected at most 1 arguments, got 9
 
 
3.2 time.ctime([ secs])
官方描述:
time. ctime ( [ secs ] )

Convert a time expressed in seconds since the epoch to a string representing local time. If secs is not provided or None, the current time as returned by time() is used. ctime(secs) is equivalent to asctime(localtime(secs)). Locale information is not used by ctime().

译文:
把一个时间戳(用秒计算的浮点数)转换为一个表示本地时间的字符串。如果参数secs未给出或为None,就使用由time()返回的当前时间。ctime(secs)的作用与asctime(localtime(secs))相同,只是使用方法不同而已。ctime()不使用时区信息。
注意    (1)ctime()、localtime()的时间戳都是使用time()获取的。
   (2)ctime()、localtime()调用的时候都可以不传入参数,此时两者都是默认调用time()函数。
ctime()与asctime()的比较程序:
>>> import time
>>> asctime = time.asctime(time.localtime()) 
>>> ctime = time.ctime(time.time())
>>> asctime
'Wed Jan 10 09:43:42 2018' 
>>> ctime
'Wed Jan 10 09:44:51 2018'
>>> type(asctime) #说明ctime()与asctime() 输出的内容完全相同(值相同、类型相同)。
<class 'str'>
>>> type(ctime)
<class 'str'>
ctime()与asctime()的异同点
异:两者参数不同。ctime([secs])的参数是时间戳(常用time.time()获得),而asctime([t])的参数是时间元组(常用localtime()或gmtime())。
同:两者输出时间的格式相同。

3.3 time.gmtime() 

官方描述:

time.gmtime([secs])

Convert a time expressed in seconds since the epoch to a struct_time in UTC in which the dst flag is always zero. If secs is not provided or None, the current time as returned by time() is used. Fractions of a second are ignored. See above for a description of the struct_time object. Seecalendar.timegm() for the inverse of this function.

译文:

将一个时间戳(以秒表示的时间)转换为UTC中的struct_time,其中dst标志始终为零。如果未提供secsNone,则使用由time()返回的当前时间。忽略秒的分数。有关struct_time对象的说明,请参见上文。有关此函数的逆函数,请参见calendar.timegm()

注:

DST:Daylight Saving Time,表面意思——阳光节约时,常用说法——夏令时。 有的地方也称其“节能时”,为什么这么称呼呢?因为人们利用夏季天亮的早这一自然现象,认为地将时间提前一小时。这样就可以使人们早起早睡,以充分利用光照资源,减少照明时间,从而节约照明用电。

关于gmtime()使用的使用,将与接下来要说的localtime()对比来讲。

3.4 time.localtime([secs])

官方描述:
time. localtime ( [ secs ] )

Like gmtime() but converts to local time. If secs is not provided or None, the current time as returned by time() is used. The dst flag is set to 1 when DST applies to the given time.

译文:

time.localtime([secs])

gmtime()相似,但结果是转换为本地时间。如果未提供secsNone,则使用由time()返回的当前时间。若给定时间使用的是夏令时,就将dst标志设置为1。

gmtime()与localtime()的异同点
同:
(1) 两者的参数相同,都是时间戳。若没有提供参数,都会自动调用time .time()得到时间戳。
  (2) 两者返回的结果格式相同,都是'Sun Jun 20 23:21:051993'
异:
两者返回的时间是两个时区对相同时刻的时间表示。其中,gmtime()表示的是0时区的标准时间,而localtime()表示的是本地时区的时间。

程序举例:
>>> import time
>>> [time.gmtime(),time.localtime()] #只有tm_hour相差8个小时,其他都相同。(笔者本地采用东八区时间,相差8个时区。)
[time.struct_time(tm_year=2018, tm_mon=1, tm_mday=10, tm_hour=7, tm_min=49, tm_sec=55, tm_wday=2, tm_yday=10, tm_isdst=0), time.struct_time(tm_year=2018, tm_mon=1, tm_mday=10, tm_hour=15, tm_min=49, tm_sec=55, tm_wday=2, tm_yday=10, tm_isdst=0)]
>>> [time.asctime(time.gmtime()),time.asctime(time.localtime())] #两个时间相差8个小时。
['Wed Jan 10 07:53:35 2018', 'Wed Jan 10 15:53:35 2018']
而我们平时采用的一般是函数time.localtime()。

3.5 time.strftime(format[t])

官方描述:

译文:

gmtime()localtime()返回的时间元组或struct_time转换为与参数格式相同的字符串。如果未提供t,则使用localtime()返回的当前时间。参数format[,t]必须是字符串。如果t中的任何字段超出允许范围,则会引发ValueError(原文为:ValueError is raised if any field in t is outside of the allowed range.

0,在时间元组中的任何位置,都是合法参数;如果通常是非法的,则该值被强制为正确的值。( if it is normally illegal the value is forced to a correct one.

以下指令可以嵌入format字符串中。它们没有可选的字段宽度和精度规范,并由strftime()结果中指示的字符替换:

Python中时间日期格式化符号:

指示 含义 笔记
%a Locale的缩写工作日名称。  
%A Locale的整个工作日名称。  
%b 语言环境的缩写月份名称。  
%B Locale的完整月份名称。  
%c 语言环境的适当日期和时间表示。  
%d 一个十进制数字[01,31]。  
%H 小时(24小时制),十进制数[00,23]。  
%I 小时(12小时制)十进制数[01,12]。  
%j 一年中的十进制数[001,366]。  
%m 月为十进制数[01,12]。  
%M 以十进制数分钟[00,59]。  
%p Locale相当于AM或PM。 (1)
%S 秒为十进制数[00,61]。 (2)
%U 年的星期数(星期日为星期的第一天)为十进制数[00,53]。在第一个星期日之前的新的一年的所有天被认为是在第0周。 (3)
%w 工作日为十进制数[0(星期日),6]。  
%W 年的星期数(星期一作为星期的第一天)作为十进制数[00,53]。在第一个星期一之前的新的一年中的所有天被认为是在第0周。 (3)
%x 语言环境的适当日期表示。  
%X 语言环境的适当时间表示。  
%y 年,无世纪作为十进制数[00,99]。  
%Y 年份以世纪为十进制数。  
%z 指示与+ HHMM或-HHMM形式的UTC / GMT的正或负时差的时区偏移,其中H表示十进制小时数字,M表示十进制分数字[-23:59,+23:59]。  
%Z 时区名称(如果没有时区,则不包含字符)。  
%% 字面值'%'字符。  

笔记:

  1. 使用函数strptime() 时,如果指令%I用于hour, 指令%p仅影响输出的hour,
  2. 范围真的是061;值60在表示闰秒的时间戳中有效,且历史原因支持值61
  3. 当与strptime()函数一起使用时,%U%W仅在计算中使用星期和年份指定。

以下是一个示例,它是与 RFC 2822 Internet电子邮件标准中指定的日期兼容的日期格式。[1]

>>>
>>> from time import gmtime, strftime
>>> strftime("%a, %d %b %Y %H:%M:%S +0000", gmtime())
'Thu, 28 Jun 2001 14:17:15 +0000'

在某些平台上可能支持附加指令,但只有在此列出的指令具有由ANSI C标准化的含义。要查看平台上支持的所有格式代码集,请参阅strftime(3)文档。

在某些平台上,可选字段宽度和精度规范可以紧跟在以下顺序的指令的初始'%'之后:这也不便携。除了%j,字段宽度通常为2,其中它为3。

虽然关于函数time.strftime()的介绍非常复杂,但使用起来很简单。
>>> import time
>>> time.strftime("%Y-%m-%d %H:%M:%S",time.gmtime()) #显示时区的时间
'2018-01-10 13:10:28'
>>> time.strftime("%Y-%m-%d %H:%M:%S",time.localtime()) #显示本地时间
'2018-01-10 21:09:45'
>>> time.strftime("%Y-%m-%d %H:%M:%S") #默认调用time.localtime()获取本地时间
'2018-01-10 21:11:19'
在各种场合中,自己调整字符串的格式即可。但一定要符合时间日期的格式化符号。

3.6 time.strptime(string [,format] )
官方描述:


译文:

time.strptime(string[format])

按照格式format,解析表示时间的字符串string。返回值是struct_time类型,类似于gmtime()localtime()

参数format使用的指令与函数strftime()所使用的相同;默认使用"%a %b %d %H:%M:%S %Y",与ctime()返回的格式匹配。如果string不能按照format解析,或者在解析后有多余的数据存在,则会引发ValueError。

The format parameter uses the same directives as those used by strftime(); it defaults to "%a %b %d %H:%M:%S %Y" which matches the formatting returned by ctime()如果string不能根据格式解析,或者如果解析后有过多的数据,则会引发ValueErrorThe default values used to fill in any missing data when more accurate values cannot be inferred are (1900, 1, 1, 0, 0, 0, 0, 1, -1). 如果缺失了某些数据或难以推断出更加精准的数据,默认值(1900, 1, 1, 0, 0, 0, 0, 1, -1)会被填充进去。stringformat必须是字符串。

例如:

>>>
>>> import time
>>> time.strptime("30 Nov 00", "%d %b %y")   
time.struct_time(tm_year=2000, tm_mon=11, tm_mday=30, tm_hour=0, tm_min=0,
                 tm_sec=0, tm_wday=3, tm_yday=335, tm_isdst=-1)

%Z指令的支持基于tzname中包含的值以及daylight是否为真。因为这一点,它是平台特定的,除了识别总是已知的UTC和GMT(并且被认为是非夏令时区域)。

仅支持文档中指定的指令。因为strftime()是在每个平台上实现的,它有时可以提供比列出的更多的指令。但是strptime()独立于任何平台,因此不一定支持所有未被记录为支持的指令。

与strftime()相似,虽然介绍很复杂,但使用起来很简单。例如:
>>> import time
>>> struct_time = time.strptime("30 Nov 00" ,"%d %b %y")
>>> print(struct_time) #注意默认值的填充
time.struct_time(tm_year=2000, tm_mon=11, tm_mday=30, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=3, tm_yday=335, tm_isdst=-1)
该函数相当于strptime()的逆函数了。


3.7 time.time()

官方描述:

译文:
time.time()

返回以秒为单位表示的时间。请注意,即使时间总是作为浮点数返回,但并不是所有系统都为时间提供比1秒更好的精度。虽然此函数通常返回非递减值,但如果系统时钟已在两次调用之间回退,则它可以返回比上一次调用更低的值。

>>> time.time()
1515592901.552844
通常,以此函数的获取时间戳,然后作为其他函数的输入参数。

3.8 time.mktime(t)

官方描述:

译文:
time.mktime(t)

这是localtime()的反函数。Its argument is the struct_time or full 9-tuple (since the dst flag is needed; use -1 as the dst flag if it is unknown) which expresses the time in local time, not UTC. 为了与time()兼容,它返回一个浮点数。如果输入值不能表示为有效时间,则会引发OverflowErrorValueError(这取决于无效值是由Python还是基础C库)。它可以生成时间的最早日期是平台相关的。

>>> import time
>>> [time.time(),time.localtime(time.time()),time.mktime(time.localtime(time.time()))]
[1515593108.0110633, time.struct_time(tm_year=2018, tm_mon=1, tm_mday=10, tm_hour=22, tm_min=5, tm_sec=8, tm_wday=2, tm_yday=10, tm_isdst=0), 1515593108.0]

该函数相当于函数time()的逆函数。