Python学习13-15.1-15.12 保持时间、计划任务和启动程序

Python学习13-15.1-15.12 保持时间、计划任务和启动程序

  • 15.1 time模块
    • 15.1.1 time.time()函数
    • 15.1.2 time.sleep()函数
  • 15.3 超级秒表
  • 15.4 datetime模块
    • 15.4.1 timedelta数据类型
    • 15.4.2 暂停至特定日期
    • 15.4.3 将datetime对象转换为字符串
    • 15.4.3 将字符串转换为datetime对象
  • 15.6 多线程
  • 内容来源

本文为学习python编程时所记录的笔记,仅供学习交流使用。

15.1 time模块

15.1.1 time.time()函数

UNIX纪元 1970年1月1日 0点 UTC 世界协调时间
time.time()函数返回自那一刻以来的秒数

>>> import time
>>> time.time()
1586417375.268444
import time
def calcProd():#calculate the product of the first 100000 numbersproduct=1for i in range(1,100000):product=product*ireturn productstartTime=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))

15.1.2 time.sleep()函数

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

round函数四舍五入

>>> import time
>>> now=time.time()
>>> now
1586417998.5821133
>>> round(now,2)
1586417998.58
>>> round(now,4)
1586417998.5821
>>> round(now)
1586417999

15.3 超级秒表

#! python3
# stopwatch.py - A simple stopwatch programimport time
#Display the program's instructions
print('Press Enter to begin.Afterwards,press enter to click the stopwatch,press crtl+c to quit')
input()
print('started')
startTime=time.time()
lastTime=startTime
lapNum=1try: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+=1lastTime=time.time()
except KeyboardInterrupt:print('\nDone.')

15.4 datetime模块

>>> import datetime
>>> datetime.datetime.now()
datetime.datetime(2020, 4, 9, 15, 43, 14, 419594)
>>> dt=datetime.datetime(2015,10,21,16,29,0)
>>> dt.year, dt.month,dt.day
(2015, 10, 21)
>>> dt.hour,dt.minute,dt.second
(16, 29, 0)

UNIX纪元时间戳可以通过datetime.datetime.fromtimestamp()转换为datetime对象

>>> datetime.datetime.fromtimestamp(1000000)
datetime.datetime(1970, 1, 12, 21, 46, 40)
>>> datetime.datetime.fromtimestamp(time.time())
datetime.datetime(2020, 4, 9, 15, 48, 25, 146852)
>>> halloween2015=datetime.datetime(2015,10,31,0,0,0)
>>> newyears2016=datetime.datetime(2016,1,1,0,0,0)
>>> now=datetime.datetime(2020,4,9,15,53,0)
>>> halloween2015==now
False
>>> halloween2015>newyears2016
False
>>> newyears2016>halloween2015
True
>>> newyears2016!=now
True

15.4.1 timedelta数据类型

表示一段时间

>>> delta=datetime.timedelta(days=9,hours=15,minutes=55,seconds=18)
>>> delta.days,delta.seconds,delta.microseconds
(9, 57318, 0)
>>> delta.total_seconds()
834918.0
>>> str(delta)
'9 days, 15:55:18'

换成VSCODE

import 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))

输出:
11 36548 0
986948.0
11 days, 10:09:08

import datetime
dt=datetime.datetime.now()
print(dt)
thousandDays=datetime.timedelta(days=1000)
print(dt+thousandDays)

输出:
2020-04-15 17:15:48.965647
2023-01-10 17:15:48.965647

import datetime
oct21st=datetime.datetime(2015,10,21,16,29,0)
aboutThirtyYears=datetime.timedelta(days=365*30)
print(oct21st)
print(oct21st-aboutThirtyYears)
print(oct21st-(2*aboutThirtyYears))

输出:
2015-10-21 16:29:00
1985-10-28 16:29:00
1955-11-05 16:29:00

15.4.2 暂停至特定日期

import datetime
import time
halloween2016=datetime.datetime(2020,4,15,17,25,35)
while datetime.datetime.now()<halloween2016:print('haha')time.sleep(1)

15.4.3 将datetime对象转换为字符串

import datetime
ost21st=datetime.datetime(2015,10,21,16,30,0)
print(ost21st.strftime('%Y/%m/%d %H:%M:%S'))
print(ost21st.strftime('%I:%M %p'))
print(ost21st.strftime("%B of '%y'"))

输出
2015/10/21 16:30:00
04:30 PM
October of ‘15’

15.4.3 将字符串转换为datetime对象

print(datetime.datetime.strptime('October 21,2015','%B %d,%Y'))
print(datetime.datetime.strptime('2015/10/21 16:29:00','%Y/%m/%d %H:%M:%S'))
print(datetime.datetime.strptime("October of '15","%B of '%y"))
print(datetime.datetime.strptime("November of '63","%B of '%y"))

输出
2015-10-21 00:00:00
2015-10-21 16:29:00
2015-10-01 00:00:00
2063-11-01 00:00:00

15.6 多线程

#! python3
#multidownloadXKCD.py - Downloads xkcd comics using multiple threads.import requests, os, bs4, threading
os.makedirs('xkcd',exist_ok=True) # store comics in ./xkcddef downloadXkcd(startComic, endComic):for urlNumber in range(startComic,endComic):#Download the page.print('Downloading page http://xkcd.com/%s...'%(urlNumber))res = requests.get('http://xkcd.com/%s'%(urlNumber))res.raise_for_status()soup=bs4.BeautifulSoup(res.text)#Find the URL of the comic image.comicElem=soup.select('#comic img')if comicElem==[]:print('Could not find comic image.')else:comicUrl=comicElem[0].get('src')#Download the image.print('Downloading image %s...'%(comicUrl))res=requests.get(comicUrl)res.raise_for_status()#save the image to ./xkcdimageFile=open(os.path.join('xkcd',os.path.basename(comicUrl)),'wb')for chunk in res.iter_content(100000):imageFile.write(chunk)imageFile.close()# Create and start the Thread objects.
downloadThreads = [] # a list of all the Thread objects
for i in range(0, 1400, 100): # loops 14 times, createS 14 threadsdownloadThread = threading.Thread(target=downloadXkcd,args=(i,i+99))downloadThreads.append(downloadThread)downloadThread.start()#wait for all threads to end
for downloadThread in downloadThreads:downloadThreads.join()
print('Done.')

内容来源

[1] [美]斯维加特(Al Sweigart).Python编程快速上手——让繁琐工作自动化[M]. 王海鹏译.北京:人民邮电出版社,2016.7.p279-301


本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!

相关文章

立即
投稿

微信公众账号

微信扫一扫加关注

返回
顶部