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 : qmeng1128@163.com
#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')

这里写图片描述

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 "<pyshell#26>", line 1, in <module>
    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 : qmeng1128@163.com
# 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')
<subprocess.Popen object at 0x00000229D62884A8>
>>> import subprocess
>>> subprocess.Popen('C:\\windows\\System32\\calc.exe')
<subprocess.Popen object at 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'])
<subprocess.Popen object at 0x00000284552A8860>

用默认程序打开

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

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

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值