Python学习笔记(十三)——保持时间、计划任务和启动程序以及多线程

time模块

time.time()函数

>>> import time
>>> time.time()
1518508607.2039714

计算程序的运行时间

import time
def func():
    p = 1
    for i in range(1,100000):
        p = p * i
    return p
startTime = time.time()
result = func()
endTime = time.time()
print('The result is %s digit long.'%(len(str(result))))
print('运行时间为%s秒'%(endTime - startTime))

这里写图片描述

time.sleep()

time.sleep(1)

数字四舍五入

>>> import time
>>> now = time.time()
>>> now
1518509648.6278894
>>> round(now)
1518509649
>>> round(now,2)
1518509648.63
>>> round(now,4)
1518509648.6279

小实验——超级秒表

#! python3
#stopwatch.py - 
#Usage:
#
#Author : qmeng
#MailTo : [email protected]
#QQ     : 1163306125
#Blog   : http://blog.csdn.net/Mq_Go/
#Create : 2018-02-13 16:18:46
#Version: 1.0
#
import time
print('Press ENTER to begin.Afterwards,\npress ENTER to "click" the stopwatch \nPress Ctrl+C to quit.')
input()
print('Started...')
startTime = time.time()
lastTime = startTime
lapNum = 1;

#记录并打印单圈时间
try:
    while True:
        input()
        temp = time.time()
        lapTime = round(temp-lastTime,2)
        lastTime = temp
        totalTime = round(time.time()-startTime,2)
        print('第 %s 圈,用时 %s 秒,总用时 %s 秒'%(lapNum,lapTime,totalTime))
        lapNum += 1
except KeyboardInterrupt:
    print('\nDone')

Python学习笔记(十三)——保持时间、计划任务和启动程序以及多线程_第1张图片

datetime模块

>>> import datetime
>>> datetime.datetime.now()
datetime.datetime(2018, 2, 13, 16, 46, 43, 329479)
>>> dt = datetime.datetime(2015,10,21,16,29,0)
>>> dt
datetime.datetime(2015, 10, 21, 16, 29)
>>> dt.year,dt.month
(2015, 10)
>>> dt.minute
29
>>> datetime.datetime.fromtimestamp(1000000)
datetime.datetime(1970, 1, 12, 21, 46, 40)
>>> datetime.datetime.fromtimestamp(time.time())
datetime.datetime(2018, 2, 13, 16, 50, 38, 529726)

timedelta数据类型

>>> delta = datetime.timedelta(days = 11,hours = 10 ,minutes = 9,seconds=8)
>>> delta.days
11
>>> delta.seconds
36548
>>> delta.hours
Traceback (most recent call last):
  File "", line 1, in 
    delta.hours
AttributeError: 'datetime.timedelta' object has no attribute 'hours'
>>> delta.microseconds
0

delta = datetime.timedelta() 接受的关键字为,weeks,days,hours,minutes,seconds,milliseconds,microseconds
这些数字保存在days,seconds、microseconds

>>> dt = datetime.datetime.now()
>>> dt
datetime.datetime(2018, 2, 13, 17, 5, 54, 408274)
>>> thousandDays = datetime.timedelta(days=1000)
>>> dt+thousandDays
datetime.datetime(2020, 11, 9, 17, 5, 54, 408274)
>>> sTime = datetime.datetime(2018,2,13,17,9,0)
>>> ThirtyYears = datetime.timedelta(days=365*30)
>>> sTime - ThirtyYears
datetime.datetime(1988, 2, 21, 17, 9)
>>> sTime - (2*ThirtyYears)
datetime.datetime(1958, 2, 28, 17, 9)

暂停至特定时间

>>> import datetime
>>> import time
>>> hello2018 = datetime.datetime(2018,2,15,0,0,0)
>>> while datetime.datetime.now() < hello2018:
    time.sleep(1)

将datetime对象转换为字符串

strftime指令 含义
%Y 四位数的年份
%y 两位是的年份
%m 数字表示的月份,01-12
%B 完整的月份,例如’November’
%b 简写的月份,例如‘Nov’
%d 一月中的第几天,01-31
%j 一年中的第几天,001-366
%w 一周中的第几天,0(周日)-6(周六)
%A 完整的周几,例如‘Monday’
%a 缩写的周几,eg:Mon
%H 小时(00-23)hopur
%h 小时(00-12)hour
%M 分(00-59)minutes
%S 秒(00-59)second
%p ‘AM’或者‘PM’
%% 就是‘%’字符
>>> oct = datetime.datetime.now()
>>> oct.strftime('%Y/%m/%d %p %I:%M:%S')
'2018/02/13 PM 08:30:19'
>>> oct.strftime('%B of %y')
'February of 18'
>>> oct.strftime('%j/365 %d/%m %w/week')
'044/365 13/02 2/week'

将字符串转换成datetime对象

>>> oct.strftime('%B %d %Y')
'February 13 2018'
>>> datetime.datetime.strptime('February 13 2018','%B %d %Y')
datetime.datetime(2018, 2, 13, 0, 0)

多线程

import threading,time
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() 函数的argskwargs 关键字参数

>>> import threading
>>> threadObj = threading.Thread(target=print,args=['Cat','Dogs','Frogs'],kwargs={'sep':'&'})
>>> threadObj.start()
Cat&
>>> Dogs&Frogs

并发问题

小实验——多线程下载XKCD

#! python3
# mulitdownloadXkcd.py - 
# Usage:
#
# Author : qmeng
# MailTo : [email protected]
# QQ     : 1163306125
# Blog   : http://blog.csdn.net/Mq_Go/
# Create : 2018-02-13 21:31:39
# Version: 1.0
#

import requests,os,bs4,threading
os.makedirs('XKCD',exist_ok=True)

def downloadXkcd(startComic,endComic):
    #Download rhe page
    for urlNumber in range(startComic,endComic):
        print('Downloading page http://xkcd.com/%s...\n'%(urlNumber))
        res = requests.get('http://xkcd.com/%s'%(urlNumber))
        try:
            res.raise_for_status()
        except requests.exceptions.HTTPError:
            print('Not Found for url: https://xkcd.com/0')
            continue
        soup = bs4.BeautifulSoup(res.text,"html.parser")

        #find the url od the comic image
        comicElem = soup.select('#comic img')
        if comicElem == []:
            print('Could not find comic image '+ urlNumber +'...\n')
        else:
            comicUrl = comicElem[0].get('src')
            comicUrl = 'http:'+ comicUrl
            print('Downloading image %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 = [] #a list of all the Thread objects
for i in range(0,1400,100):
    downloadThread = threading.Thread(target=downloadXkcd,args=(i,i+3))
    downloadThreads.append(downloadThread)
    downloadThread.start()

#等待所有的线程结束
for downloadThread in downloadThreads:
    downloadThread.join()
print('Done...')

从Python启动其他程序

打开计算器

>>> import subprocess
>>> subprocess.Popen('C:\\windows\\System32\\calc.exe')
0x00000229D62884A8>
>>> import subprocess
>>> subprocess.Popen('C:\\windows\\System32\\calc.exe')
0x00000229D62884A8>
>>> 
>>> re = subprocess.Popen('C:\\windows\\System32\\calc.exe')
>>> re.poll() == None
True
>>> re.poll()
0
>>> re.wait()
0

向Popen()传递命令行参数

>>> subprocess.Popen([r'D:\install\Sublime Text 3\sublime_text.exe',r'D:\python\abcdef.py'])
0x00000284552A8860>

用默认程序打开

>>> subprocess.Popen(['start','D:\\python\\dictionary.txt'],shell=True)
0x00000284552A8AC8>

小实验——简单的倒计时程序

你可能感兴趣的:(Python)