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 ...
随机推荐
- UWP DEP0700: 应用程序注册失败。[0x80073CF9] Install failed. Please contact your software vendor. (Exception from HRESULT: 0x80073CF9)
现在部署的app项目八成是从以前的一个项目复制过来,修改的.或者本地存在一个相同的app没有卸载. 解决方法: 1. 卸载之前相同的app 2.如果是复制的项目A,但是经过修改后变成了项目B,并且A和 ...
- 【PaPaPa】集成B/S主流技术的MVC5项目 - 实干派:说做就做,我们已经起航,你还在观望吗
我们是谁 我们是C#爱好者,互相分享技术,一起学习一起成长一起做一个项目. 我们是开源爱好者,从我们手上出来的代码都会托管在源代码管理平台(oschina),到目前为止不收费,将来也不会出现任何收费情 ...
- docker-compose 部署 EFK
信息: Docker版本($ docker --version):Docker版本18.06.1-ce,版本e68fc7a 系统信息($ cat /etc/centos-release):CentOS ...
- python接口自动化2-发送post请求
发送post的请求参考例子很简单,实际遇到的情况却是很复杂的,首先第一个post请求肯定是登录了,但登录是最难处理的.登录问题解决了,后面都简单了. 一.查看官方文档 1.学习一个新的模块,其实不用去 ...
- centos7安装vim以及在vim中显示中文
1.centos7安装vim yum -y install vim(简单粗暴安装方法) 2.在vim中显示中文不出现乱码 (1).vim ~/.vimrc (~/.vimrc为vim配置文件) (2) ...
- WebGL实现sprite精灵效果的GUI控件
threejs已经有了sprite插件,这就方便了three的用户,直接可以使用threejs的sprite插件来制作GUI模型.sprite插件是阿里的lasoy老师改造过的,这个很厉害,要学习一哈 ...
- 三种UIScrollView嵌套实现方案
背景 随着产品功能不断的迭代,总会有需求希望在保证不影响其他区域功能的前提下,在某一区域实现根据选择器切换不同的内容显示. 苹果并不推荐嵌套滚动视图,如果直接添加的话,就会出现下图这种情况,手势的冲突 ...
- MyEclipse 和 eclipse 最简单的安装Jetty容器插件
一.MyEclipse安装jetty 1.下载jetty插件 http://pan.baidu.com/s/1nuMYGNv 2.将下载后的jetty插件放到安装MyEclipse目录的MyEcli ...
- word2vec的理解
在学习LSTM的时候,了解了word2vec,简单的理解就是把词变成向量.看了很多书,也搜索了很多博客,大多数都是在word2vec的实现原理.数学公式,和一堆怎么样重新写一个word2vec的pyt ...
- [转载]GBK 汉字内码扩展规范编码表(1.0 版)
编码表源地址:http://ff.163.com/newflyff/gbk-list/ 编码在线查询:http://www.qqxiuzi.cn/bianma/zifuji.php GBK 汉字内码扩 ...