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) |
%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 | 当前时区的名称 |
%% | %号本身 |
利用 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)