python常用的时间方法

我们先导入必须用到的一个module
>>> import time
设置一个时间的格式,下面会用到
>>>ISOTIMEFORMAT=’%Y-%m-%d %X’
看一下当前的时间,和其他很多语言相似这是从epoch(1970 年 1 月 1 日 00:00:00)开始到当前的秒数。
>>> time.time()
1180759620.859
上面的看不懂,换个格式来看看
>>> time.localtime()
(2007, 6, 2, 12, 47, 7, 5, 153, 0)
localtime返回tuple格式的时间,有一个和它类似的函数叫gmtime(),2个函数的差别是时区,gmtime()返回的是0时区的值,localtime返回的是当前时区的值。
>>> time.strftime( ISOTIMEFORMAT, time.localtime() )
‘2007-06-02 12:54:29′
用上我们的时间格式定义了,使用strftime对时间做一个转换,如果取现在的时间,time.localtime() 可以不用。

>>> time.strftime( ISOTIMEFORMAT, time.localtime( time.time() ) )
‘2007-06-02 12:54:31′
>>> time.strftime( ISOTIMEFORMAT, time.gmtime( time.time() ) )
‘2007-06-02 04:55:02′
上面展示了gmtime和localtime的区别。
查看时区用
>>> time.timezone
-28800
上面的值是一个秒值,是当前时区和0时区相差的描述,-28800=-8*3600,即为东八区。

帖几个简单的函数

def ISOString2Time( s ):
    ”’
    convert a ISO format time to second
    from:2006-04-12 16:46:40 to:23123123
    把一个时间转化为秒
    ”’
    return time.strptime( s, ISOTIMEFORMAT )
def Time2ISOString( s ):
    ”’
    convert second to a ISO format time
    from: 23123123 to: 2006-04-12 16:46:40
    把给定的秒转化为定义的格式
    ”’
    return time.strftime( ISOTIMEFORMAT, time.localtime( float( s ) ) )
def dateplustime( d, t ):
    ”’
    d=2006-04-12 16:46:40
    t=2小时
   return  2006-04-12 18:46:40
   计算一个日期相差多少秒的日期,time2sec是另外一个函数,可以处理,3天,13分钟,10小时等字符串,回头再来写这个,需要结合正则表达式。
    ”’
    return Time2ISOString( time.mktime( ISOString2Time( d ) )+time2sec( t ) )
def dateMinDate( d1, d2 ):
    ”’
    minus to iso format date,return seconds
    计算2个时间相差多少秒
    ”’
    d1=ISOString2Time( d1 )
    d2=ISOString2Time( d2 )
    return time.mktime( d1 )-time.mktime( d2 )

Share and Enjoy:
  • Print this article!
  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Mixx
  • Google Bookmarks
  • LinkedIn
  • Live
  • MySpace
  • RSS
  • Slashdot
  • Technorati
  • TwitThis

Related posts:

  1. Python 多线程 XML RPC的实现

Leave a Reply

 

 

 

You can use these HTML tags

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

*
To prove you're a person (not a spam script), type the security word shown in the picture. Click on the picture to hear an audio file of the word.
Click to hear an audio file of the anti-spam word

Contact us

Admin: Bryan Wu