time / subprocess / datetime -- 时间任务

Unix 时间戳是编程常用参考时间:1970年1月1日0点,即 UTC (协调世界时) ;




time 模块


time.time() 返回自那一刻(1970年1月1日0点)以来的秒数,是一个浮点值,这个数字称为 UNIX 纪元时间戳;

import time
print(time.time()) # 返回当前 UNIX 纪元时间戳

运行结果:
1567058652.7356534

利用 UNIX 纪元时间戳计算程序运行时间

import time

def calcProd():
    product = 1
    for i in range(1, 100000):
        product = product * i
    return product

startTime = time.time()
print('Time start at ' + str(startTime))
prod = calcProd()
endTime = time.time()
print('Time end   at ' + str(endTime))
print('The result is %s digits long ,' % (len(str(prod))))
print('Took %s seconds to calculate.' % (endTime - startTime))

运行结果:
Time start at 1566464814.2718549
Time end at 1566464816.7103047
The result is 456569 digits long ,
Took 2.4384498596191406 seconds to calculate.

实现延时

time.sleep() 该函数可让程序暂停相应的秒数;

import time

while (1):
    print('Tick')
    time.sleep(1)
    print('Tock')
    time.sleep(1)

把时间戳转换为字符串

time ctime(sec) 把时间戳输入参数转换为字符串(格式:Tue Feb 17 10:00:18 2013),缺省值为 time.time() 时间戳

from time import ctime
print(ctime()) # 返回当前时间戳的字符串形式
print(ctime(10)) # 返回自 UTC 十秒后的时间的字符串形式

运行结果:
Mon Sep 2 16:04:52 2019
Thu Jan 1 08:00:10 1970




round() - 浮点数四舍五入(计算)


import time

now = time.time()
print(now)
print(round(now, 2))  # 四舍五入精度为小数点后两位
print(round(now, 4))
print(round(now))  # 四舍五入到整数



subprocess 模块


利用 subprocess 模块中的 Popen() 函数P 表示 process,进程),可在同一个程序中打开多个线程;(每个在同一程序中打开的实例都是同一个程序的不同进程,如打开 Web 浏览器的多个窗口,每个窗口都是 Web 浏览器程序的不同进程)
每个进程可含多个线程,进程无法直接读写另一个进程的变量而线程可以,进程之间是相对独立的存在;

import subprocess

calcProc = subprocess.Popen('C:\\Windows\\System32\\calc.exe')  # 创建 Popen 对象
print(calcProc.poll())
print(calcProc.wait())
print(calcProc.poll())

运行结果:
None
0
0

Popen 对象poll()方法相当于询问进程是否执行完毕已给的代码,若该进程在poll()被调用时仍在运行,则 poll() 方法返回 None,否则返回一个整数并退出代码(进程无错终止返回0,有一个错误终止返回1……);
Popen 对象wait() 方法用于等待进程完成执行代码,该方法将阻塞程序直到被启动的进程运行终止;


Popen() 方法传递命令行参数

Popen() 传递一个列表,作为唯一的参数,该列表中的第一个字符串是要启动的程序的可执行文件名,所有后续的字符串将是该程序启动时,传递给该程序的命令行参数;(即以第一个字符串的程序去启动后续程序)

import subprocess
# 将打开 notepad.exe 应用程序 和 以 notepad 的方式启动 hello.txt 
subprocess.Popen(['C:\\Windows\\notepad.exe','E:\\Python_file\\draft\\hello.txt'])

利用默认的应用程序打开文件

Popen() 传入的列表的第一个元素为 start,则后续的文件将以 Windows 系统默认的应用程序打开文件;

import subprocess, os, logging

logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
os.getcwd()  # 指向当前工作目录

logging.info('Current working path is : ' + str(os.getcwd()))
fileObj = open('hello.txt', 'w')
fileObj.write('Hellow world!')
fileObj.close()
subprocess.Popen(['start', 'hello.txt'], shell=True)  # 以默认程序打开文件



datetime 模块


更方便的日期显示与处理模块;
datetime.datetime.now() 获取当前时间并格式化

print(datetime.datetime.now())
dt = datetime.datetime(2015, 10, 21, 16, 29, 0)
print(dt.year, dt.minute, dt.second)

运行结果;
2019-08-26 14:25:32.326928
2015 29 0

转换 Unix 纪元时间戳为日期显示格式

datetime.datetime.fromtimestamp() 转换 Unix 纪元时间戳为 datetime 格式

import datetime, time

curTime = time.time()
print(datetime.datetime.fromtimestamp(curTime))  # Unix 纪元时间戳转换为 datetime 对象

运行结果:
2019-08-26 14:28:33.483548

timedelta 对象

timedelta 对象表示的是一段时间,很方便地应用于计算时间差;

import datetime

# datetime.timedelta() 中的参数可选,默认值为0,无 years 和 months
delta = datetime.timedelta(weeks=10, days=11, hours=10, minutes=9, seconds=8, milliseconds=50, microseconds=45)
print(delta)  # 以默认格式显示时间
# 分别以何种格式显示时间,其中 delta.seconds 以秒显示10小时9分8秒,delta.microseconds 以毫秒显示50毫秒+45微秒(1ms = 1000us)
print(delta.days, delta.seconds, delta.microseconds)
print(delta.total_seconds())  # 计算并显示总秒数

运行结果:
81 days, 10:09:08.050045
81 36548 50045
7034948.050045

python内部只以 days, seconds 和 microseconds 三个单位作为存储的基本单位

参数单位转换规则如下:

  • 1毫秒会转换成1000微秒。
  • 1分钟会转换成60秒。
  • 1小时会转换成3600秒。
  • 1星期会转换成7天。

timedelta 输入参数值的取值范围

0 <= microseconds < 1000000
0 <= seconds < 3600*24 (一天的秒数)
-999999999 <= days <= 999999999

timedalte 的三个只读属性

timedelta.min:负数最大时间差,相当于 timedelta(-999999999);
timedelta.max:正数最大时间差,相当于 timedelta(days=999999999, hours=23, minutes=59, seconds=59, microseconds=999999);
timedelta.resolution:两个时间的最小差值 相当于 timedelta(microseconds=1);

如果标准化后的 days 数值超过了指定范围,将会抛出 OverflowError 异常。

利用 timedelta 对象计算时间差

timedelta 对象支持加减乘除、比较等运算;

from datetime import datetime, timedelta
import logging

logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
select_ele = ''
data_els = []
today_ele = datetime.now().date()

logging.info('datetime.now().date() : ' + str(today_ele))
data_els.append(['今天', datetime.now().date()])
data_els.append(['昨天', today_ele - timedelta(days=1)])
data_els.append(['近7天', today_ele - timedelta(days=7)])
data_els.append(['近30天', today_ele - timedelta(days=30)])
print('data_els : ' + str(data_els))

运行结果:
2019-08-26 15:28:06,270 - INFO - datetime.now().date() : 2019-08-26
data_els : [[‘今天’, datetime.date(2019, 8, 26)], [‘昨天’, datetime.date(2019, 8, 25)], [‘近7天’, datetime.date(2019, 8, 19)], [‘近30天’, datetime.date(2019, 7, 27)]]

利用 srtftime() 方法将 datetime 对象转换为字符串

Unix 纪元时间戳datetime 对象对人可读性较差,利用 srtftime()方法可将 datetime 对象转换为字符串形式显示;(srtftime·中的f 表示"格式"的意思 format“数据格式”
其使用方法类似于字符串格式化的使用;

from datetime import datetime
import logging

logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
oct21st = datetime(2019, 8, 26, 15, 59, 26)

logging.info('oct21st : ' + str(oct21st))
print(oct21st.strftime('%Y/%m/%d  %H:%M:%S'))
print(oct21st.strftime('%I:%M %p'))
print(oct21st.strftime('%B of %y'))

运行结果:
2019-08-26 16:03:52,632 - INFO - oct21st : 2019-08-26 15:59:26
2019/08/26 15:59:26
03:59 PM
August of 19

strftime 参数含义
%y两位数的年份表示(00-99)
%Y四位数的年份表示(000-9999)
%m月份(01-12)
%d月内中的一天(0-31)
%H24小时制小时数(0-23)
%I12小时制小时数(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当前时区的名称
%%%号本身

利用 strptime() 方法将字符串转换成 datetime 对象

也就是 strftime() 的反转换,使用的入口参数同 strftime()

from datetime import datetime

print(datetime.strptime('October 21,2015', '%B %d,%Y'))

运行结果:
2015-10-21 00:00:00




例程


秒表

import time

print('Press ENTER to begin. Afterwards, press ENTER to "click" the stopwatch. Press Ctrl-C to quit.')
input()
print('Started.')
startTime = time.time()
lastTime = startTime
lapNum = 1

try:
    while True:
        input()
        lapTime = round(time.time() - lastTime, 2)
        totalTime = round(time.time() - startTime, 2)
        # end=''参数可避免输出重复空行
        print('Lap #%s: Total time: %s(Lap Time: %s)' % (lapNum, totalTime, lapTime), end='')
        lapNum += 1
        lastTime = time.time()  # reset the last lap time
except KeyboardInterrupt:
    print('\nDone')

简易倒计时

import logging, time, subprocess, os

logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')

logging.info('Current working path is : ' + str(os.getcwd()))
timeLeft = 10
while timeLeft > 0:
    print(timeLeft)
    time.sleep(1)
    timeLeft = timeLeft - 1
subprocess.Popen(['start', 'timeout.txt'], shell=True)

定制定时器(Github

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Truffle7电子

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值