1、最常用的time.time()返回的是一个浮点数,单位为秒。
-
In [65]: time.time()
-
Out[65]: 1383814130.224978
2、strftime处理的类型是time.struct_time,实际上是一个tuple。
3、那如何获得struct_time类型呢?strptime和localtime都会返回这个类型。
-
In [66]: time.localtime()
-
Out[66]: time.struct_time(tm_year=2013, tm_mon=11, tm_mday=7, tm_hour=16, tm_min=58, tm_sec=2, tm_wday=3, tm_yday=311, tm_isdst=0)
-
In [69]: time.strftime("%Y%m%d",time.localtime())
-
Out[69]: '20131107'
-
In [70]: time.strptime('20131107',"%Y%m%d")
-
Out[70]: time.struct_time(tm_year=2013, tm_mon=11, tm_mday=7, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=3, tm_yday=311, tm_isdst=-1)
有个练习题(来源于网上):
python脚本清除linux cron中过期的定时计划
主要是对计划任务文件里的时间格式化、与当下时间做对比,代码如下(大部分来自互联网)
-
#!/usr/bin/env python
-
#-*- coding: utf-8 -*-
-
import time
-
file = open("crontab.file")
-
context = file.readlines()
-
file = open("crontab.file","w")
-
for line in context:
-
#不处理注释行,空行
-
if not line.strip().startswith('#') and len(line.strip()) > 1:
-
t=' '.join(line.strip().split()[:4]) #获取 分 时 天 月
-
if '*' not in t:
-
#print t_cron
-
tt=str(time.localtime()[0]) + ':' + ':'.join(t.split()[::-1])#构造2013:11:7:17:13格式 ,[::-1]字符串反转技巧
-
t_cron=time.mktime(time.strptime(tt,'%Y:%m:%d:%H:%M'))#获取浮点数时间
-
#print t,tt,t_cron
-
now = time.time()
-
if now < t_cron:
-
file.write(line)
-
else:
-
file.write(line)#周期执行的保留写回文件
-
-
else:
-
file.write(line)#注释行,空行写回文件
-
-
file.close()
阅读(4114) | 评论(0) | 转发(0) |