pyhon处理时间,定时任务和启动程序

你可以守在电脑旁边查看程序的运行,但不守着它运行就更爽了。 你可以使用定时任务在指定的时间运行,或者固定的间隔时间运行。 例如, 你的程序每隔一小时爬取一下网站,来检测内容是否发生变化,或者在你睡觉的时候(每天凌晨4点)启动一个CPU消耗很大的任务。 Python的 time 和 datetime modules 提供了这些功能。

你也可以编写程序来启动其他程序, 通过使用 subprocess 和 threading modules。 通常,编写程序最快的方式是利用其他人已经写好的应用程序。

The time Module

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

The time.time() Function

Unix纪元(Unix epoch) 是编程中常用的时间参考:上午12点1970年1月1日,协调世界时(UTC)。 time.time() function 返回自该时刻起的秒数作为浮点值。(回想一下,浮点数只是一个带小数点的数字。)这个数字是称为纪元时间戳。 例如,在交互中输入以下内容 shell:

Python 3.5.2 (default, Nov 12 2018, 13:43:14) 
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import time
>>> time.time()
1554271653.4386587
>>> 

Epoch时间戳可用于分析代码效率,即测量一段代码需要运行多长时间。调用time.time()计算开始时间,然后调用代码,再计算结束时间。算出代码运行消耗的时间:

#! /usr/bin/python3
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))

# output
The result is 456569 digits long.
Took 3.525928497314453 seconds to calculate.

注意
分析代码的另一种方法是使用提供的 cProfile.run() 函数比简单的 time.time() 技术更具信息性的细节。 cProfile.run() 的详情可以参考这里

The time.sleep() Function

如果需要暂停程序一段时间,请调用 time.sleep() 函数并传递您希望程序保持暂停的秒数。在交互式shell中输入以下内容:

Python 3.5.2 (default, Nov 12 2018, 13:43:14) 
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import time
>>> for i in range(3):
...     print('Tick')
...     time.sleep(1)
...     print('Tock')
...     time.sleep(1)
... 
Tick
Tock
Tick
Tock
Tick
Tock
>>> time.sleep(5)
>>> 

for循环将打印 Tick ,暂停一秒,打印 Tock,暂停一秒,打印勾选,暂停,知道三次循环完。time.sleep() 函数将被阻塞 - 也就是说,它不会返回和释放你的程序执行其他代码 - 直到你的秒数
传递给 time.sleep() 已经过去了。 例如,如果输入 time.sleep(5) ,你会等待五秒后才看到下一个提示(>>>)。
请注意,在在IDLE中,按ctrl -C不会中断 time.sleep() 调用。 IDLE会等到整个暂停结束后再提高KeyboardInterrupt 异常。 要解决这个问题,不是调用单个time.sleep(30) 暂停30秒,而是使用for循环30次调用time.sleep(1)。
如果你在这30秒内的某个时间按ctrl -C,你应该看到立即抛出KeyboardInterrupt异常。

Rounding Numbers

在处理时间时,您经常会遇到很多浮点值小数点后的数字。 为了使这些值更易于使用,您可以
使用 Python 的内置 round() 函数缩短它们,该函数将浮点数舍入到您指定的精度。 只需传入你想要的数字,加上一个可选的第二个参数,表示在deci-之后有多少位数你要把它绕到它。 如果省略第二个参数,round() 将您的数字四舍五入到最接近的整数。 输入以下内容
交互式shell:

Python 3.5.2 (default, Nov 12 2018, 13:43:14) 
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import time
>>> now = time.time()
>>> now
1554274051.5462723
>>> round(now, 2)
1554274051.55
>>> round(now, 4)
1554274051.5463
>>> round(now)
1554274052
>>> 

在导入时间并存储 time.time() 之后,我们调用 round(now, 2) 现在四舍五入到小数点后的两位数,round(now, 4) 到四舍五入小数点后的数字, round(now) 舍入到最接近的整数。

Project: Super Stopwatch

如果你想统计一个任务花了多少时间,没有物理秒表,又很难找到一个现成的APP. 你可以用Python写一个。
从高层次来看,这是您的计划将要做的事情:

  • 跟踪按下回车键之间经过的时间,每次按键开始计时器上的新“lap”。
  • 记录下圈数,总时间和单圈时间。
    这意味着您的代码需要执行以下操作:
  • 在程序开始时以及每圈开始时, 通过调用 time.time() 查找当前时间并将其存储为时间戳.
  • 保持一个计数器计数器并在每次用户按下输入时递增它。
  • 通过减去时间戳来计算经过的时间。
  • 处理 KeyboardInterrupt 异常,以便用户可以按ctrl -C退出。
#! /usr/bin/python3
# stopwatch.py - A simple stopwatch program.

import time

# Display the program's instructions.
print('Press ENTER to begin. Afterwards. press ENTER to "click" the stopwatch. Press Ctrl-C to quit.')
input()  # press Enter to begin
print('Started.')
startTime = time.time() # get the first lap's start time
lastTime = startTime
lapNum = 1

# Start tracking the lap times.
try:
    while True:
        input()
        lapTime = round(time.time() - lastTime, 2)
        totalTime = round(time.time() - startTime, 2)
        print('Lap #%s: %s (%s)' % (lapNum, totalTime, lapTime), end='')
        lapNum += 1
        lastTime = time.time() # reset the last lap time
except KeyboardInterrupt:
    # Handle the Ctrl-C exception to keep its error message from displaying.
    print('\nDone.')

将时间错转换成 datetime object

Python 3.5.2 (default, Nov 12 2018, 13:43:14) 
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import datetime
>>> datetime.datetime.fromtimestamp(1000000)
datetime.datetime(1970, 1, 12, 21, 46, 40)
>>> import time
>>> datetime.datetime.fromtimestamp(time.time())
datetime.datetime(2019, 4, 3, 16, 33, 12, 603559)
>>> 

datatime object 可以对比时间

Python 3.5.2 (default, Nov 12 2018, 13:43:14) 
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import datetime
>>> halloween2015 = datetime.datetime(2015, 10, 31, 0, 0, 0)
>>> newyears2016 = datetime.datetime(2016, 1, 1, 0, 0, 0)
>>> oct31_2015 = datetime.datetime(2015, 10, 31, 0, 0, 0)
>>> halloween2015 == oct31_2015
True
>>> halloween2015 > newyears2016
False
>>> newyears2016 > halloween2015
True
>>> newyears2016 != oct31_2015
True
>>> 
The timedelta Data Type

datetime module 也提供了一个 timedelta data type, 代表一个持续时间而不是一个时刻。

Python 3.5.2 (default, Nov 12 2018, 13:43:14) 
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import datetime
>>> delta = datetime.timedelta(days=11, hours=10, minutes=9, seconds=8)
>>> delta.days,delta.seconds,delta.microseconds
(11, 36548, 0)
>>> delta.total_seconds()
986948.0
>>> 


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值