Chinaunix首页 | 论坛 | 博客
  • 博客访问: 12121
  • 博文数量: 3
  • 博客积分: 30
  • 博客等级: 民兵
  • 技术积分: 30
  • 用 户 组: 普通用户
  • 注册时间: 2010-10-12 16:48
文章分类

全部博文(3)

文章存档

2013年(3)

我的朋友

分类: Python/Ruby

2013-11-07 17:05:23


1、最常用的time.time()返回的是一个浮点数,单位为秒。

点击(此处)折叠或打开

  1. In [65]: time.time()
  2. Out[65]: 1383814130.224978
2、
strftime处理的类型是time.struct_time,实际上是一个tuple。
3、那如何获得struct_time类型呢?strptime和localtime都会返回这个类型。

点击(此处)折叠或打开

  1. In [66]: time.localtime()
  2. 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)
  3. In [69]: time.strftime("%Y%m%d",time.localtime())
  4. Out[69]: '20131107'

点击(此处)折叠或打开

  1. In [70]: time.strptime('20131107',"%Y%m%d")
  2. 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)
有个练习题(来源于网上):pythonlinux cron
主要是对计划任务文件里的时间格式化、与当下时间做对比,代码如下(大部分来自互联网)

点击(此处)折叠或打开

  1. #!/usr/bin/env python
  2. #-*- coding: utf-8 -*-
  3. import time
  4. file = open("crontab.file")
  5. context = file.readlines()
  6. file = open("crontab.file","w")
  7. for line in context:
  8.         #不处理注释行,空行
  9.         if not line.strip().startswith('#') and len(line.strip()) > 1:
  10.                 t=' '.join(line.strip().split()[:4]) #获取 分 时 天 月
  11.                 if '*' not in t:
  12.                         #print t_cron
  13.                         tt=str(time.localtime()[0]) + ':' + ':'.join(t.split()[::-1])#构造2013:11:7:17:13格式 ,[::-1]字符串反转技巧
  14.                         t_cron=time.mktime(time.strptime(tt,'%Y:%m:%d:%H:%M'))#获取浮点数时间
  15.                         #print t,tt,t_cron
  16.                         now = time.time()
  17.                         if now < t_cron:
  18.                                 file.write(line)
  19.                 else:
  20.                         file.write(line)#周期执行的保留写回文件
  21.                       
  22.         else:
  23.                 file.write(line)#注释行,空行写回文件
  24.          
  25. file.close()



阅读(4114) | 评论(0) | 转发(0) |
0

上一篇:没有了

下一篇:python判断字符串

给主人留下些什么吧!~~