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 ...
随机推荐
- CSS3新增特性详解(一)
注:由于CSS3的新特性较多,所以分两篇博文来说明.第一篇主要包括新的选择器.文字及块阴影.多背景图.颜色渐变.圆角等.第二篇主要细说CSS3的各种动画效果,如:旋转.移动.缩放等,还包括图标字体的应 ...
- charles抓包https/模拟弱网/设置断点重定向/压测
charles几个常用功能 1,ios 抓包https网页:(如未配置,会显示unknown) 第一步是:给手机安装SSL证书 手机和电脑在同一wifi下,手机wifi配置http代理,ip是电脑 ...
- Android Studio|IntelliJ IDEA 上传代码到码云
码云 新建项目 Android Studio|IntelliJ IDEA 然后仓库就创建好了 此时左方文件应显示为红色 添加代码到git仓库 提交代码到git仓库 push等待被拒绝 拉取README ...
- Git报错:Your branch is ahead of 'origin/master' by 1 commit
. commit之后,用git status,打印信息为: # On branch master # Your branch is ahead of 'origin/master' by 1 c ...
- netbeans 类重复 解决
Help -> About -> Cache directory 记录Cache directory目录 删除该目录下的所有文件 重启
- Python获取每一位的数字,并返回到列表
通过计算 def calc(value): result = [] while value: result.append(value % 10) value = value // 10 #逆序,按正常 ...
- 【python 3.6】类:访问属性及调用方法
>>> class price(): //定义1个类,用于计算价格 def __init__(self,name,danjia): //初始化方法,定义商品名称和单价 self.na ...
- [Windows][C#][.NET][WPF]基于ArcFace2.0+红外双目摄像头的活体检测
废话不多说 直接上图这个是demo中用到的双目摄像头,一个是红外的,一个是正常的rgb摄像头两个usb接口,在电脑上呈现两路摄像头通道程序检测RGB输出图像,当检测到有人脸时,用RGB人脸的位置到红外 ...
- 第十一次ScrumMeeting博客
第十一次ScrumMeeting博客 本次会议于11月29日(三)22时整在3公寓725房间召开,持续30分钟. 与会人员:刘畅.辛德泰张安澜.赵奕.方科栋. 1. 每个人的工作(有Issue的内容和 ...
- 【quickhybrid】Android端的项目实现
前言 前文中就有提到,Hybrid模式的核心就是在原生,而本文就以此项目的Android部分为例介绍Android部分的实现. 提示,由于各种各样的原因,本项目中的Android容器确保核心交互以及部 ...