本文實例講述了Python使用time模塊實現指定時間觸發器。分享給大家供大家參考,具體如下:
其實很簡單,指定某個時間讓腳本處理一個事件,比如說一個get請求~
任何語言都會有關于時間的各種方法,Python也不例外。
help(time)之后可以知道time有2種時間表示形式:
1、時間戳表示法,即以整型或浮點型表示的是一個以秒為單位的時間間隔。這個時間的基礎值是從1970年的1月1號零點開始算起。
2、元組格式表示法,即一種python的數據結構表示。這個元組有9個整型內容。分別表示不同的時間含義。
    year (four digits, e.g. 1998)
    month (1-12)
    day (1-31)
    hours (0-23)
    minutes (0-59)
    seconds (0-59)
    weekday (0-6, Monday is 0)
    Julian day (day in the year, 1-366)
    DST (Daylight Savings Time) flag (-1, 0 or 1) ##夏令時格式,0:表示正常格式,1:表示為夏令時格式,-1:表示根據當前的日期時間格式來判定
time() 或者datetime.now() -- 返回當前時間戳,浮點數形式。不接受參數clock() -- 返回當前程序的cpu執行時間。unix系統始終返回全部運行時間;而windows從第二次開始都是以第一次調用此函數時的時間戳作為基準,而不是程序開始時間為基準。不接受參數。sleep() -- 延遲一個時間段,接受整型、浮點型。
gmtime() -- 將時間戳轉換為UTC時間元組格式。接受一個浮點型時間戳參數,其默認值為當前時間戳。
localtime() -- 將時間戳轉換為本地時間元組格式。接受一個浮點型時間戳參數,其默認值為當前時間戳。
asctime() -- 將時間元組格式轉換為字符串形式。接受一個時間元組,其默認值為localtime()返回值
ctime() -- 將時間戳轉換為字符串。接受一個時間戳,其默認值為當前時間戳。等價于asctime(localtime(seconds))
mktime() -- 將本地時間元組轉換為時間戳。接受一個時間元組,必選。
strftime() -- 將時間元組以指定的格式轉換為字符串形式。接受字符串格式化串、時間元組。時間元組為可選,默認為localtime()
strptime() -- 將指定格式的時間字符串解析為時間元組,strftime()的逆向過程。接受字符串,時間格式2個參數,都是必選。
并且其類型還可以做減法操作 然后用total_seconds()可以將某個時間差值轉換為s,具體看后續代碼部分
示例代碼:
import httplibimport timedef doFirst():  from datetime import datetime, timedelta  curTime = datetime.now()  #print curTime  desTime = curTime.replace(hour=3, minute=0, second=0, microsecond=0)  #print desTime  delta = desTime-curTime  #print delta  skipSeconds = int(delta.total_seconds())  #print skipSeconds  if skipSeconds==0:    return True  else:    if skipSeconds<0:      skipSeconds+=24*60*60    print "Must sleep %d seconds" % skipSeconds    return False#也可以采取獲取當前時間差值然后自己計數,不過考慮誤差問題,就不采取了def getTime():  from datetime import datetime, timedelta  curTime = datetime.now()  #print curTime  desTime = curTime.replace(hour=3, minute=0, second=0, microsecond=0)  #print desTime  delta = desTime-curTime  #print delta  skipSeconds = int(delta.total_seconds())  if skipSeconds<0:    skipSeconds+=24*60*60  print skipSeconds  return skipSecondsdef gethttp():  url = "URL"  conn = httplib.HTTPConnection("IP")  conn.request(method="GET",url=url)  response = conn.getresponse()  res= response.read()  print res#getTime()while True:  if doFirst():    gethttp()    time.sleep(24*59*60)  time.sleep(1)s.close()            
| 
 
 | 
新聞熱點
疑難解答