• 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(' Done.')                

    ####当输入一个人的名字时,用当前的时间记录下他们进入或离开的时间

    ####显示自一项处理开始以来的时间

    ####间歇性地检查程序已经运行了多久,并为用户提供一个机会,取消耗时太久的任务

    #################################多线程##############################################

    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(' Done.')                 

    ##############################################################################

    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.')

             

  • 相关阅读:
    WAVECOM CDMA Modem 发送短信
    【转】关于正则表达式匹配任意字符(包括换行符)的写法
    MS2000 差异备份 还原
    推荐一款非常适用的弹框 phpcms v9都用的这个!!!!
    正则截取内容
    javascript面向对象编程实现
    一次 全部删除MSSQL数据库用户表,存储过程
    【转】 jQuery图片预加载+等比例缩放
    多种多样的Loading特效
    关于图片轮播的几种思路
  • 原文地址:https://www.cnblogs.com/dudumiaomiao/p/7241877.html
Copyright © 2020-2023  润新知