>>> from env_helper import info; info()
页面更新时间: 2024-01-19 21:47:16
运行环境:
    Linux发行版本: Debian GNU/Linux 12 (bookworm)
    操作系统内核: Linux-6.1.0-17-amd64-x86_64-with-glibc2.36
    Python版本: 3.11.2

5.1. 保持时间、计划任务和启动程序

坐在电脑前运行程序是不错的,但在你没有直接监督时运 行程序,也是有用的。计算机的时钟可以调度程序,在特定的 时间和日期运行,或定期运行。例如,程序可以每小时抓取一 个网站,检查变更,或在凌晨4点你睡觉时,执行CPU密集 型任务。Python的 timedatetime 模块提供了 这些函数。

利用 subprocessthreading 模块,你也可以 编程按时启动其他程序。通常,编程最快的方法是利用 其他人己经写好的应用程序。

5.1.1. time 模块

计算机的系统时钟设置为特定的日期、时间和时区。 内置的 time 模块让Python程序能读取系统时钟的 当前时间。在 time 模块中, time.time()time.sleep() 函数是最有用的模块。

5.1.2. time.time() 函数

Unix纪元是编程中经常参考的时间:1970年1月1日0点, 即协调世界时(UTC)。 time.time() 函数返回自 那一刻以来的秒数,是一个浮点值(回想一下,浮点值 只是一个带小数点的数)。这个数字称为UNIX纪元时间戳。 例如,在交互式环境中输入以下代码:

>>> import time
>>> time.time()
1705672036.169943

这里,我在2015年2月27日,太平洋标准时间11:05 (或7:05 PM UTC),调用 time.time() 。返回值 是Unix 纪元的那一刻与 time.time() 被 调用的那一刻之间的秒数。

注意

交互式环境的例子得到的日期和时间,是我在2015年2月 写这一章的时间。除非你是时间旅行者,否则得到的日期 和时间会不同。

纪元时间戳可以用于剖析代码,也就是测量一段代码的 运行时间。如果在代码块开始时调用 time.time() , 并在结束时再次调用,就可以用第二个时间戳减去第一个, 得到这两次调用之间经过的时间。例如,打开一个新的 文件编辑器窗口,然后输入以下程序:

>>> import time
>>> def calcProd():
>>>     # Calculate the product of the first 100,000 numbers.'
>>>     product = 1
>>>     for i in range(1,100000):
>>>         product = product*i
>>>     return product
>>>
>>> startTime = time.time()
>>> prod = calcProd()
>>> endTime = time.time()
>>> print('The result is %s digits long.' % (len(str(prod))))
>>> print('Took %s seconds to calculate.' % (endTime -startTime))
---------------------------------------------------------------------------

ValueError                                Traceback (most recent call last)

Cell In [3], line 12
     10 prod = calcProd()
     11 endTime = time.time()
---> 12 print('The result is %s digits long.' % (len(str(prod))))
     13 print('Took %s seconds to calculate.' % (endTime -startTime))


ValueError: Exceeds the limit (4300 digits) for integer string conversion; use sys.set_int_max_str_digits() to increase the limit

在1行,我们定义了函数calcProd(),循环遍历1至99999的整数, 返回它们的乘积。在2行,我们调用time.time(),将结果保存在 startTime中。调用calcProd()后,我们再次调用 time.time(),将结果保存endTime中。最后我们打印 calcProd() 返回的乘积的长度,以及运行calcProd() 的时间。

将该程序保存为 calcProd.py ,并运行它。输出看起来像这样:

注意

另一种剖析代码的方法是利用cProfile.run()函数。 与简单的 time.time() 技术相比,它提供了详细的信息。 cProfile.run() 函数在 https://docs.python.Org/3/library/profile.html 有解释。

5.1.3. time.sleep() 函数

如果需要让程序暂停一下,就调用 time.sleep()函数, 并传入希望程序暂停的秒数。在交互式环境中输入以下代码:

>>> import time
>>> for i in range(3):
>>>     print('Tick')
>>>     time.sleep(1)
>>>     print('Tock')
>>>     time.sleep(1)
>>> time.sleep(5)

for 循环将打印 Tick,暂停一秒钟,打印 Tock , 暂停一秒钟,打印 Tick,暂停,如此继续, 直到 TickTock 分别被打印3次。

time.sleep() 函数将阻塞(也就是说,它不会返回或 让程序执行其他代码),直到传递给 time.sleep() 的 秒数流逝。例如,如果输入 time.sleep(5),会在5秒后才看 到下一个提示符( >>> )。

请注意,在 IDLE 中按Ctrl-C不会中断 time.sleep() 调用。IDLE 会等待到暂停结束, 再抛出 Keyboardlnterrupt 异常。要绕过这个问题, 不要用一次 time.sleep(10) 调用来暂停10秒, 而是使用 for 循环执行 10 次 time.sleep(1)调用。

>>> import time
>>> for i in range(10):
>>>     time.sleep(1)

如果在这10秒内的某个时候按Ctrl-C, 应该马上看到拋出 Keyboardlnterrupt 异常。

5.1.4. Python3 日期和时间

Python 程序能用很多方式处理日期和时间, 转换日期格式是一个常见的功能。

Python 提供了一个 timecalendar 模块 可以用于格式化日期和时间。

时间间隔是以秒为单位的浮点小数。

每个时间戳都以自从1970年1月1日午夜(历元) 经过了多长时间来表示。

Python 的 time 模块下有很多函数可以转换常见日期格式。 如函数 time.time() 用于获取当前时间戳, 如下实例:

>>> #!/usr/bin/python3
>>>
>>> import time;  # 引入time模块
>>>
>>> ticks = time.time()
>>> print ("当前时间戳为:", ticks)

时间戳单位最适于做日期运算。但是1970年之前的日期就无法 以此表示了。太遥远的日期也不行,UNIX和Windows只支持到2038年。

5.1.5. 什么是时间元组?

很多Python函数用一个元组装起来的9组数字处理时间:

序号  |字段|    
----|----|----|
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

5.1.6. 获取当前时间

从返回浮点数的时间辍方式向时间元组转换, 只要将浮点数传递给如 localtime 之类的函数。

>>> #!/usr/bin/python3
>>>
>>> import time
>>>
>>> localtime = time.asctime( time.localtime(time.time()) )
>>> print ("本地时间为 :", localtime)

5.1.7. 格式化日期

我们可以使用 time 模块的 strftime 方法来格式化日期,:

time.strftime(format[, t])
>>> #!/usr/bin/python3
>>>
>>> import time
>>>
>>> # 格式化成2016-03-20 11:45:39形式
>>> print (time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))
>>>
>>> # 格式化成Sat Mar 28 22:24:24 2016形式
>>> print (time.strftime("%a %b %d %H:%M:%S %Y", time.localtime()))
>>>
>>> # 将格式字符串转换为时间戳
>>> a = "Sat Mar 28 22:24:24 2016"
>>> print (time.mktime(time.strptime(a,"%a %b %d %H:%M:%S %Y")))

5.1.8. python中时间日期格式化符号:

  • %y 两位数的年份表示(00-99)

  • %Y 四位数的年份表示(000-9999)

  • %m 月份(01-12)

  • %d 月内中的一天(0-31)

  • %H 24小时制小时数(0-23)

  • %I 12小时制小时数(01-12)

  • %M 分钟数(00=59)

  • %S 秒(00-59)

  • %a 本地简化星期名称

  • %A 本地完整星期名称

  • %b 本地简化的月份名称

  • %B 本地完整的月份名称

  • %c 本地相应的日期表示和时间表示

  • %j 年内的一天(001-366)

  • %p 本地A.M.或P.M.的等价符

  • %U 一年中的星期数(00-53)星期天为星期的开始

  • %w 星期(0-6),星期天为星期的开始

  • %W 一年中的星期数(00-53)星期一为星期的开始

  • %x 本地相应的日期表示

  • %X 本地相应的时间表示

  • %Z 当前时区的名称

  • %% %号本身

5.1.9. 获取某月日历

Calendar 模块有很广泛的方法用来处理年历和月历,例如打印某月的月历:

>>> import calendar
>>>
>>> cal = calendar.month(2016, 1)
>>> print ("以下输出2016年1月份的日历:")
>>> print (cal)

5.1.10. Time 模块

Time 模块包含了以下内置函数,既有时间处理 相的,也有转换时间格式的:

1 time.altzone

返回格林威治西部的夏令时地区的偏移秒数。如果该地区在 格林威治东部会返回负值(如西欧,包括英国)。 对夏令时启用地区才能使用。

以下实例展示了 altzone() 函数的使用方法:

>>> import time
>>> print ("time.altzone %d " % time.altzone)

2 time.asctime([tupletime])

接受时间元组并返回一个可读的形式为 “Tue Dec 11 18:07:14 2008”(2008年12月11日 周二18时07分14秒) 的24个字符的字符串。

以下实例展示了 asctime() 函数的使用方法:

>>> import time
>>> t = time.localtime()
>>> print ("time.asctime(t): %s " % time.asctime(t))

3 time.clock()

用以浮点数计算的秒数返回当前的CPU时间。 用来衡量不同程序的耗时,比 time.time() 更有用。

5.1.11. Python3 time.process_time() 方法

描述

Python 的 time.process_time() 函数以浮点数计算的秒数返回当前的CPU时间。 用来衡量不同程序的耗时,比time.time() 更有用。

这个需要注意,在不同的系统上含义不同。在UNIX系统上, 它返回的是”进程时间”,它是用秒表示的浮点数(时间戳)。 而在WINDOWS中,第一次调用,返回的是进程运行的实际时间。 而第二次之后的调用是自第一次调用以后到现在的运行时间。 (实际上是以WIN32上 QueryPerformanceCounter() 为基础, 它比毫秒表示更为精确)

该函数有两个功能,在第一次调用的时候,返回的是程序运行的实际时间;

以第二次之后的调用,返回的是自第一次调用后,到这次调用的时间间隔

在win32系统下,这个函数返回的是真实时间(wall time), 而在Unix/Linux下返回的是CPU时间。

以下实例展示了 process_time() 函数的使用方法:

>>> import time
>>>
>>> def procedure():
>>>     time.sleep(2.5)
>>>
>>> # time.clock
>>> t0 = time.process_time()
>>> procedure()
>>> print (time.process_time() - t0)
>>> # time.time
>>> t0 = time.time()
>>> procedure()
>>> print (time.time() - t0)

4 time.ctime([secs])

作用相当于asctime(localtime(secs)), 未给参数相当于asctime()

以下实例展示了 ctime() 函数的使用方法:

>>> import time
>>> print ("time.ctime() : %s" % time.ctime())

5 time.gmtime([secs])

接收时间辍(1970纪元后经过的浮点秒数)并返回格林威治天文 时间下的时间元组t。注:t.tm_isdst始终为0

以下实例展示了 gmtime() 函数的使用方法:

>>> import time
>>> print ("gmtime :", time.gmtime(1455508609.34375))

6 time.localtime([secs]

接收时间辍(1970纪元后经过的浮点秒数)并返回当地时间下 的时间元组t(t.tm_isdst可取0或1,取决于当地当时是不是夏令时)。

以下实例展示了 localtime() 函数的使用方法:

>>> import time
>>> print ("localtime(): ", time.localtime(1455508609.34375))

7 time.mktime(tupletime)

接受时间元组并返回时间辍(1970纪元后经过的浮点秒数)。

5.1.12. Python3 time mktime() 方法

描述

Python time mktime() 函数执行与gmtime(), localtime() 相反的操作,它接收 struct_time对象作为参数,返回用秒数来表示 时间的浮点数。

如果输入的值不是一个合法的时间,将触发 OverflowErrorValueError。 语法

mktime() 方法语法:

time.mktime(t)

参数

t -- 结构化的时间或者完整的9位元组元素。

返回值

返回用秒数来表示时间的浮点数。 实例

以下实例展示了 mktime() 函数的使用方法:

>>> import time
>>>
>>> t = (2016, 2, 17, 17, 3, 38, 1, 48, 0)
>>> secs = time.mktime( t )
>>> print ("time.mktime(t) : %f" %  secs)
>>> print ("asctime(localtime(secs)): %s" % time.asctime(time.localtime(secs)))

8 time.sleep(secs)

推迟调用线程的运行,secs指秒数。

以下实例展示了 sleep() 函数的使用方法:

>>> import time
>>>
>>> print ("Start : %s" % time.ctime())
>>> time.sleep( 5 )
>>> print ("End : %s" % time.ctime())

9 time.strftime(fmt[,tupletime])

接收以时间元组,并返回以可读字符串表示的当地时间,格式由fmt决定。

以下实例展示了 strftime() 函数的使用方法:

>>> import time
>>> print (time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))

10 time.strptime(str,fmt='%a %b %d %H:%M:%S %Y')

根据fmt的格式把一个时间字符串解析为时间元组。

以下实例展示了 strftime() 函数的使用方法:

>>> import time
>>> struct_time = time.strptime("30 Nov 00", "%d %b %y")
>>> print ("返回元组: ", struct_time)

time.time() 返回当前时间的时间戳(1970纪元后经过的浮点秒数)。

以下实例展示了 time() 函数的使用方法:

>>> import time
>>> print(time.time())

5.1.13. Python3 time tzset() 方法

描述

Python time tzset() 根据环境变量TZ重新初始化时间相关设置。

标准TZ环境变量格式:

std offset [dst [offset [,start[/time], end[/time]]]]

参数

  • std 和 dst:三个或者多个时间的缩写字母。传递给 time.tzname.

  • offset: 距UTC的偏移,格式: [+|-]hh[:mm[:ss]] {h=0-23, m/s=0-59}。

  • start[/time], end[/time]: DST 开始生效时的日期。格式为 m.w.d — 代表日期的月份、周数和日期。w=1 指月份中的第一周,而 w=5 指月份的最后一周。‘start’ 和 ‘end’ 可以是以下格式之一:

    • Jn: 儒略日 n (1 <= n <= 365)。闰年日(2月29)不计算在内。

    • n: 儒略日 (0 <= n <= 365)。 闰年日(2月29)计算在内

    • Mm.n.d: 日期的月份、周数和日期。w=1 指月份中的第一周,而 w=5 指月份的最后一周。

    • time:(可选)DST 开始生效时的时间(24 小时制)。默认值为 02:00(指定时区的本地时间)。

语法

time.tzset()

参数

NA。

返回值

该函数没有返回值。 实例

以下实例展示了 tzset() 函数的使用方法:

>>> import time
>>> import os
>>>
>>> os.environ['TZ'] = 'EST+05EDT,M4.1.0,M10.5.0'
>>> time.tzset()
>>> print (time.strftime('%X %x %Z'))
>>>
>>> os.environ['TZ'] = 'AEST-10AEDT-11,M10.5.0,M3.5.0'
>>> time.tzset()
>>> print (time.strftime('%X %x %Z'))

Time 模块包含了以下2个非常重要的属性:

序号

属性及描述

1

time.timezone 属性 time.timezone是当地时 区(未启动夏令时)距 离格林威治的偏移秒数 (>0,美洲;<=0大部分 欧洲,亚洲,非洲)。

2

time.tzname 属性time.tzn ame包含一对根据情况的 不同而不同的字符串, 分别是带夏令时的本地 时区名称,和不带的。

5.1.14. 日历(Calendar)模块

此模块的函数都是日历相关的,例如打印某月的字符月历。

星期一是默认的每周第一天,星期天是默认的最后一天。 更改设置需调用 calendar.setfirstweekday() 函数。 模块包含了以下内置函数:

序号| 函数及描述
----|----|----|
1|  calendar.calendar(year,w=2,l=1,c=6)返回一个多行字符串格式的year年年历,3个月一行,间隔距离为c。 每日宽度间隔为w字符。每行长度为21* W+18+2* C。l是每星期行数。
2|  calendar.firstweekday( )返回当前每周起始日期的设置。默认情况下,首次载入caendar模块时返回0,即星期一。
3|  calendar.isleap(year)是闰年返回True,否则为false。
4   |calendar.leapdays(y1,y2)返回在Y1,Y2两年之间的闰年总数。
5   |calendar.month(year,month,w=2,l=1)返回一个多行字符串格式的year年month月日历,两行标题,一周一行。每日宽度间隔为w字符。每行的长度为7* w+6。l是每星期的行数。
6|  calendar.monthcalendar(year,month)返回一个整数的单层嵌套列表。每个子列表装载代表一个星期的整数。Year年month月外的日期都设为0;范围内的日子都由该月第几日表示,从1开始。
7   |calendar.monthrange(year,month)返回两个整数。第一个是该月的星期几的日期码,第二个是该月的日期码。日从0(星期一)到6(星期日);月从1到12。
8   |calendar.prcal(year,w=2,l=1,c=6)相当于 print calendar.calendar(year,w,l,c).
9   |calendar.prmonth(year,month,w=2,l=1)相当于 print calendar.calendar(year,w,l,c)。
10  |calendar.setfirstweekday(weekday)设置每周的起始日期码。0(星期一)到6(星期日)。
11  |calendar.timegm(tupletime)和time.gmtime相反:接受一个时间元组形式,返回该时刻的时间辍(1970纪元后经过的浮点秒数)。
12  |calendar.weekday(year,month,day)返回给定日期的日期码。0(星期一)到6(星期日)。月份为 1(一月) 到 12(12月)。

5.1.15. 其他相关模块和函数

在Python中,其他处理日期和时间的模块还有:

  • time 模块

  • datetime 模块