17.1:time模块
time模块让python程序能读取系统时钟的当前时间
17.1.1:time.time()函数
import time
print(time.time())
time.time()函数:返回1970年1月1日0点以来的秒数
import time
print(time.ctime())
thisMoment = time.time()
print(time.ctime(thisMoment))
time.ctiem():返回一个关于当前时间的字符串,如果传入time.time()函数返回的UNIX纪元以来的秒数,得到一个时间的字符串
17.1.2:time.sleep()函数
import time
for i in range(3):
print('Tick')
time.sleep(1)
time.sleep()函数:让程序暂停几秒
17.2:数字四舍五入
import time
now = time.time()
print(round(now, 2))
print(round(now, 4))
print(round(now))
round()函数按照指定的精度四舍五入一个浮点数,第一个参数代表要处理的数字,第二个参数代表精确到几位小数,如果省略第二个参数代码四舍五入到整数
17.3:项目:超级秒表
import time
print('Press ENTER to begin. Afterward, 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)
print('Lap #%s: %s (%s)' % (lapNum, totalTime, lapTime), end='')
lapNum += 1
lastTime = time.time()
except KeyboardInterrupt:
print('\nDone')
17.4:datetime模块
import time, datetime
print(datetime.datetime.now())
dt = datetime.datetime(2019, 10, 21, 16, 29, 0)
print(dt.year, dt.month, dt.day)
print(dt.hour, dt.minute, dt.second)
print(datetime.datetime.fromtimestamp(1000000))
print(datetime.datetime.fromtimestamp(time.time()))
datetime.datetime.now():返回一个datetime对象,以表示当前的日期和时间,这个对象包含当前时刻的年、月、日、时、分、秒、微秒。
datetime.datetime.fromtimestamp():UNIX纪元时间戳可以通过该函数转换为datetime对象。
17.4.1:timedelta数据类型
import time, datetime
delta = datetime.timedelta(days=11, hours=10, minutes=9, seconds=8)
print(delta.days, delta.seconds, delta.microseconds)
print(delta.total_seconds())
print(str(delta))
timedelta:数据类型,它表示一个时刻
total_seconds()函数返回以秒表示的数据
一个timedelta对象传入str(),将返回良好的、人类可读的字符串表示形式
17.4.2:暂停直至特定时间
import time, datetime
halloween2021 = datetime.datetime(2021, 10, 1, 0, 0, 0)
while datetime.datetime.now() < halloween2021:
time.sleep()
17.4.3:将datetime()对象转换为字符串
strftime指令 | 含义 | strftime指令 | 含义 |
---|---|---|---|
%Y | 带世纪的年‘2017’ | %A | 完整的第几周‘Monday’ |
%y | 不带世纪的年‘17’ | %a | 简写的第一周‘Mon’ |
%m | 数字表示月份‘01’ | %H | 小时‘00’至‘23’ |
%B | 完整的月份‘November’ | %I | 小时‘01’至‘12’ |
%b | 简写的月份‘Nov’ | %M | 分‘00’至‘59’ |
%d | 一个月的第几天‘01’至‘31’ | %S | 秒‘00’至‘59’ |
%j | 一年中的第几天‘001’至‘366’ | %p | ‘AM’或‘PM’ |
%w | 一周的第几天‘0’至‘6’ | %% | 就是字符% |
import time, datetime
oct21st = datetime.datetime(2021, 10, 1, 0, 0, 0)
print(oct21st.strftime('%Y/%m/%d %H:%M:%S'))
strftime传入定制的格式字符串,并返回一个字符串
17.4.4:将字符串转换成datetime对象
import time, datetime
print(datetime.datetime.strptime('October 1, 2019', '%B %d, %Y'))
strptime()函数与strftime()函数相反,将一个日期信息的字符串作为第一个参数传递,格式字符串作为第二个参数,带有日期信息的字符串必须准确匹配定制的格式字符串,否则报异常
17.5:回顾python的时间函数
17.6:多线程
import time, datetime, threading
print('Start of program')
def takeANap():
time.sleep(5)
print('Wake up!')
threadObj = threading.Thread(target=takeANap)
threadObj.start()
print('End of program')
要得到单独的线程,首先要调用threading.Thread()函数来生成一个Thread对象,调用函数后传入关键字target=takeANap意味着要在新线程调用takeANap()函数
17.6.1:向线程的目标函数传递参数
import time, datetime, threading
threadObj = threading.Thread(target=print, args=['Cats', 'Dogs', 'Frogs'], kwargs={'sep': ' & '})
threadObj.start()
常规参数可以作为一个列表传递给threading.Thread()的args关键字参数
关键字参数可以作为一个字典传递给threading.Thread()的kwargs关键字参数
17.6.2:并发问题
为了避免并发问题,绝不能让多个线程读取或写入相同的变量
17.7:项目:多线程XKCD下载程序
import requests, os, bs4, threading
os.makedirs('xkcd', exist_ok=True) # 创建下载到新的文件夹
def downloadXkcd(startComic, endComic):
for urlNumber in range(startComic, endComic):
print('下载页面: %s' % urlNumber)
res = requests.get('http://***/%s' % urlNumber)
res.raise_for_status()
soup = bs4.BeautifulSoup(res.text, 'html.parser')
comicElem = soup.select('#comic img')
if comicUrl == []:
print('不能下载图像')
else:
comicUrl = 'https:' + comicElem[0].get('src')
print('下载图片 %s' % (comicUrl))
res = requests.get(comicUrl)
res.raise_for_status()
imageFile = open(os.path.join('xkcd', os.path.basename(comicUrl)), 'wb')
for chunk in res.iter_content(100000):
imageFile.write(chunk)
imageFile.close()
downloadThreads = []
for i in range(0, 140, 10):
start = i
end = i + 9
if start == 0:
start = 1
downloadThread = threading.Thread(target=downloadXkcd, args=(start, end))
downloadThreads.append(downloadThread)
downloadThread.start()
for downloadThread in downloadThreads:
downloadThread.join()
print('Done.')
17.8:从python启动其他程序
import subprocess
paintProc = subprocess.Popen('c:\\Windows\\System32\\mspaint.exe')
paintProc.poll()
paintProc.wait()
Popen函数:启动计算机中其他程序
poll()方法:检查程序是否在运行,运行返回True,否则返回False
wait()方法:终止其他程序运行
17.8.1:向Popen()传递命令行参数
import subprocess
paintProc = subprocess.Popen(['c:\\Windows\\notepad.exe', 'C:\\Users\\Al\\hello.txt'])
向Popen函数传递一个列表作为唯一参数。该列表的第一个字符串是要启动的程序的可执行文件,后续字符串将是该程序启动时。
17.8.2:Task Scheduler、launchd和cron
17.8.3:用python打开网站
17.8.4:运行其他python脚本
import subprocess
paintProc = subprocess.Popen(['c:\\***\\python.exe', '**.py'])
17.8.5:用默认的应用程序打开文件
import subprocess
fileObj = open('hello.txt', 'w')
fileObj.write('Hello, world!')
fileObj.close()
subprocess.Popen(['start', 'hello.txt'], shell=True)
shell:表示是否使用默认程序打开文件
17.9:项目:简单的倒计时程序
import time, subprocess
timeLeft = 60
while timeLeft>0:
print(timeLeft, '\n', end='')
time.sleep(1)
timeLeft = timeLeft - 1
subprocess.Popen(['start', 'alarm.wav'], shell=True)