python自动化之时间
cxz##############################现在时间#########################
import time
time.time()
############################程序跑了多久#######################
import time
def calcProd():
product=1
for i in range(1,100000):
product=product*i
return product
starttime=time.time()
result=calcProd()
endtime=time.time()
print('The result is %s digits long.'%(len(str(result))))
print('Took %s seconds to calculate.'%(endtime-starttime))
########################将程序阻塞###################################
import time
for i in range(3):
print('Tick')
time.sleep(5)
print('Tock')
time.sleep(10)
#IDLE中按Ctrl-C不会中断time.sleep()调用.IDLE会等待到暂停结束,再抛出
#KeyboardInterrupt异常.要绕出这个问题,不要用一次time.sleep(30)调用来
#暂停30秒,而是使用for循环执行30次time.sleep(1)调用
###########################获取时间戳#################################
import datetime
>>> datetime.datetime.now()
datetime.datetime(2017, 5, 25, 16, 23, 11, 702000)
>>> dt=datetime.datetime.now()
>>> dt.year,dt.month,dt.day
(2017, 5, 25)
>>> dt=datetime.datetime(2015,10,21,16,29,0)
>>> dt.year,dt.month,dt.day
(2015, 10, 21)
>>> datetime.datetime.fromtimestamp(1000000)
datetime.datetime(1970, 1, 12, 21, 46, 40)
>>> datetime.datetime.fromtimestamp(0)
datetime.datetime(1970, 1, 1, 8, 0)
#########################一段时间#####################################
import datetime
>>> delta=datetime.timedelta(days=11,hours=10,minutes=9,seconds=8)
>>> delta.days,delta.seconds,delta.microseconds
(11, 36548, 0)
>>> delta.total_seconds()
986948.0
>>> delta
datetime.timedelta(11, 36548)
############################时间设置###################################
dt=datetime.datetime.now()
thousandDays=datetime.timedelta(days=1000)
dt+thousandDays
oct21st=datetime.datetime(2015,10,21,16,29,0)
aboutThirtyYears=datetime.timedelta(days=365*30)
oct21st
oct21st-aboutThirtyYears
oct21st-(2*aboutThirtyYears)
##########################暂停直至特定日期#############################
import datetime
import time
halloween2017=datetime.datetime(2017,5,27,14,45,0)
while datetime.datetime.now()<halloween2017:
time.sleep(2) #####time.sleep(1)调用将暂停程序,这样计算机不会浪费CPU处理周期,一遍又一遍检查时间
print 'w'
####################将datetime对象与字符串互转#########################
import datetime
oct21st=datetime.datetime(2015,10,21,16,29,0)
oct21st.strftime('%Y/%m/%d %H:%M:%S')
oct21st.strftime('%I:%M %p')
oct21st.strftime("%B of '%y'")
datetime.datetime.strptime('October 21,2015','%B %d,%Y')
datetime.datetime.strptime('2015/10/21 16:29:00','%Y/%m/%d %H:%M:%S')
datetime.datetime.strptime("October of '15","%B of '%y")
######################################超级秒表########################################
# -*- coding: utf-8 -*-
"""
Created on Wed Jun 07 19:42:11 2017
@author: shenlu
"""
##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 Ctrl-C to quit.')
raw_input() #press Enter to begin
print('Started.')
starttime=time.time() #get the first lap's start time
lasttime=starttime
lapNum=1
try:
while True:
raw_input()
lapTime=round(time.time()-lasttime,2) ####单圈时间
totalTime=round(time.time()-starttime,2) ####总圈时间
print'Lap #%s:%s (%s)'%(lapNum.rjust(2),totalTime.rjust(2),lapTime.rjust(2)),
lapNum +=1 ####圈数
lasttime=time.time() #reset the last lap time
except KeyboardInterrupt:
#Handle the Ctrl-C excepetion to keep its error message from displaying.
print('\nDone.')
####当输入一个人的名字时,用当前的时间记录下他们进入或离开的时间
####显示自一项处理开始以来的时间
####间歇性地检查程序已经运行了多久,并为用户提供一个机会,取消耗时太久的任务
#################################多线程##############################################
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.')
##############并发问题:为了避免并发问题,绝不让多个线程读取或写入相同的变量###########
##############当创建一个新的Thread对象时,要确保其目标函数只使用该函数中的局部变量#####
import threading
threadObj=threading.Thread(target=print,args=['cats','Dogs','Frogs'],kwargs={'sep':' & '})
threadObj.start()
#####################################################################################
################################多进程###############################################
####################如果想在python脚本中启动一个外部程序,就将该程序的文件名
####################传递给subprocess.Popen()
import subprocess
subprocess.Popen('C:\\Windows\\notepad.exe')
calcProc=subprocess.Popen('C:\\Windows\\notepad.exe')
calcProc.poll()==None ####调用时,若程序仍在运行,则返回None
calcProc.wait() ####阻塞,直到启动的进程终止
calcProc.poll() ####当wait()与poll()返回0时,说明该进程终止且无错
##########################向Popen()传递命令行参数####################################
subprocess.Popen(['C:\\Windows\\notepad.exe','C:\\Windows\\sl_loss_rate.SQL'])
#####webbrowser.open()函数可以从程序启动Web浏览器,打开指定的网站
#####而不是用subprocess.Popen()打开浏览器应用程序
######运行其他python脚本
subprocess.Popen(['C:\\Python27\\python.exe','C:\\Python27\\Lib\\site-packages\\xy\\stopwatch.py'])
'''Windows上的Task Scheduler,OS X上的launchd,或Linux上的cron调度程序.
这些工具文档齐全,而且可靠,它们都允许你安排应用程序在特定的时间启动.
'''
####用默认的应用程序打开文件
fileObj=open('hello.txt','w')
fileObj.write('Hello world!')
fileObj.close()
import subprocess
subprocess.Popen(['start','hello.txt'],shell=True)
#########################简单的倒计时程序####################################
######从60倒数###############################################################
######倒数至0时播放声音文件##################################################
import time,subprocess
timeleft=60
while timeleft>0:
print timeleft,
time.sleep(1)
timeleft=timeleft-1
#TODO:At the end of the countdown,play a sound file.
subprocess.Popen(['start','alarm.wav'],shell=True)
#############################################################################
# -*- coding: utf-8 -*-
"""
Created on Mon Jun 12 14:29:01 2017
@author: sl
"""
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')
##############################################################################
# -*- coding: utf-8 -*-
"""
Created on Wed Jun 07 19:42:11 2017
@author: shenlu
"""
##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 Ctrl-C to quit.')
raw_input() #press Enter to begin
print('Started.')
starttime=time.time() #get the first lap's start time
lasttime=starttime
lapNum=1
try:
while True:
raw_input()
lapTime=round(time.time()-lasttime,2)
totalTime=round(time.time()-starttime,2)
print'Lap #%s:%s (%s)'%(str(lapNum).rjust(2),str(totalTime).rjust(10),str(lapTime).rjust(10)),
lapNum +=1
lasttime=time.time() #reset the last lap time
except KeyboardInterrupt:
#Handle the Ctrl-C excepetion to keep its error message from displaying.
print('\nDone.')
##############################################################################
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()
####TODO:Create and start the Thread objects
downloadThreads=[] ###a list of all the Thread objects
for i in range(0,1000,100): ###loops 14 times,create 14 threads
downloadThread=threading.Thread(target=downloadThread,args=(i,i+99))
downloadThreads.append(downloadThread)
downloadThread.start()
####TODO:wait for all threads to end
for downloadThread in downloadThreads:
downloadThread.join()
print('Done.')
python自动化之时间的更多相关文章
- flow.ci + Github + Slack 一步步搭建 Python 自动化持续集成
理想的程序员必须懒惰,永远追随自动化法则.Automating shapes smarter future. 在一个 Python 项目的开发过程中可能会做的事情:编译.手动或自动化测试.部署环境配置 ...
- Day1 老男孩python自动化运维课程学习笔记
2017年1月7日老男孩python自动化运维课程正式开课 第一天学习内容: 上午 1.python语言的基本介绍 python语言是一门解释型的语言,与1989年的圣诞节期间,吉多·范罗苏姆为了在阿 ...
- python自动化运维学习第一天--day1
学习python自动化运维第一天自己总结的作业 所使用到知识:json模块,用于数据转化sys.exit 用于中断循环退出程序字符串格式化.format字典.文件打开读写with open(file, ...
- Python自动化培训第一周学习总结
Python自动化培训第一周学习结束,看视频复习,把作业完成了. 总体来说,开卷有益. 首先,工具真是好东西,能够极大提升效率,也是人区别于动物所在.想起前任大领导对工具的不屑,本质也是对效率的不屑, ...
- Appium+python自动化8-Appium Python API
Appium+python自动化8-AppiumPython API 前言: Appium Python API全集,不知道哪个大神整理的,这里贴出来分享给大家. 1.contexts conte ...
- selenium+python自动化98--文件下载弹窗处理(PyKeyboard)
前言 在web自动化下载操作时,有时候会弹出下载框,这种下载框不属于web的页面,是没办法去定位的(有些同学一说到点击,脑袋里面就是定位!定位!定位!) 有时候我们并不是非要去定位到这个按钮再去点击, ...
- Python自动化面试必备 之 你真明白装饰器么?
Python自动化面试必备 之 你真明白装饰器么? 装饰器是程序开发中经常会用到的一个功能,用好了装饰器,开发效率如虎添翼,所以这也是Python面试中必问的问题,但对于好多小白来讲,这个功能 有点绕 ...
- Selenium2+python自动化55-unittest之装饰器(@classmethod)
前言 前面讲到unittest里面setUp可以在每次执行用例前执行,这样有效的减少了代码量,但是有个弊端,比如打开浏览器操作,每次执行用例时候都会重新打开,这样就会浪费很多时间. 于是就想是不是可以 ...
- Selenium2+python自动化39-关于面试的题
前言 最近看到群里有小伙伴贴出一组面试题,最近又是跳槽黄金季节,小编忍不住抽出一点时间总结了下, 回答不妥的地方欢迎各位高手拍砖指点. 一.selenium中如何判断元素是否存在? 首先selen ...
随机推荐
- 用 Python 破解 WIFI 密码,走到哪里都能连 WIFI
WIFI 破解,Python 程序员必学技能.WIFI 已经完全普及,现在 Python 程序员没网,走到哪里都不怕! 教你们一招,如何在图片中提取 Python 脚本代码.图片发送至手机 QQ 长按 ...
- 深入理解JavaScript是如何实现继承的
深入理解JavaScript是如何实现继承的-----------http://www.jb51.net/article/44384.htm
- Ubuntu18.04安装Python3.6.8
Ubuntu18.04预装了Python3.6.5 终于不再预装Python2.7了 但是系统预装的Python分散安装在各个目录里 以后改起来非常不方便 所以本次安装Python3.6.8 Pyth ...
- js数组知识点总结及经典笔试题
1.判断数组 这是笔试里经常会出现的知识考察点,总结一下 (1)Array.isArray()方法判断 var a=[]; Array.isArray(a) //返回true var b='hello ...
- javascript this(上)
javascript的this指向的是一个函数运行时动态绑定对象. this的4种常见的指向: 作为对象的方法调用 var obj={ name:"姚小白", getName:fu ...
- GitHub笔记(三)——分支管理和多人协作
三.分支管理 0 语句: 查看分支:git branch 创建分支:git branch <name> 切换分支:git checkout <name> 创建+切换分支:git ...
- Redis源码阅读(六)集群-故障迁移(下)
Redis源码阅读(六)集群-故障迁移(下) 最近私人的事情比较多,没有抽出时间来整理博客.书接上文,上一篇里总结了Redis故障迁移的几个关键点,以及Redis中故障检测的实现.本篇主要介绍集群检测 ...
- centos7.6 安装 openvpn--2.4.7
openvpn-server端 搭建 1,软件版本 Centos - 7.x easy-rsa - 3.0.3 OpenVPN - 2.4.7 2,安装 建议安装启用epel源,采用yum的方式安装o ...
- 投稿007期|令人震惊到发指的PyObject对象代码设计之美
前言 最近在重温经典漫画<SlamDunk>的全国大赛篇,其中的一个情形可以很好的诠释虎躯一震这个状态——当樱木看到流川枫一次高难度投篮时内心的感受:“经过两万次射球练习后,樱木首次明白到 ...
- PSP总结报告1
回答作业问题 1.回想一下你曾经对计算机专业的畅想 我高考后报考的是计算机科学与技术,当时对计算机技术基本了解为零,当时以为什么东西都会用到计算机,学计算机以后不会找不到工作,刚开学的时候对计算机一窍 ...