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


本文为学习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 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))

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 program

import 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=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.')

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 ./xkcd

def 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 ./xkcd
            imageFile=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 threads
    downloadThread = 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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值