本文实例讲述了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()
新闻热点
疑难解答