From:http://www.juyimeng.com/python-common-time-function.html
我們先導(dǎo)入必須用到的一個module
>>> import time
設(shè)置一個時間的格式,下面會用到
>>>ISOTIMEFORMAT=’%Y-%m-%d %X’
看一下當(dāng)前的時間,和其他很多語言相似這是從epoch(1970 年 1 月 1 日 00:00:00)開始到當(dāng)前的秒數(shù)。
>>> time.time()
1180759620.859
上面的看不懂,換個格式來看看
>>> time.localtime()
(2007, 6, 2, 12, 47, 7, 5, 153, 0)
localtime返回tuple格式的時間,有一個和它類似的函數(shù)叫g(shù)mtime(),2個函數(shù)的差別是時區(qū),gmtime()返回的是0時區(qū)的值,localtime返回的是當(dāng)前時區(qū)的值。
>>> time.strftime( ISOTIMEFORMAT, time.localtime() )
’2007-06-02 12:54:29′
用上我們的時間格式定義了,使用strftime對時間做一個轉(zhuǎn)換,如果取現(xiàn)在的時間,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的區(qū)別。
查看時區(qū)用
>>> time.timezone
-28800
上面的值是一個秒值,是當(dāng)前時區(qū)和0時區(qū)相差的描述,-28800=-8*3600,即為東八區(qū)。
帖幾個簡單的函數(shù)
def ISOString2Time( s ):
'''
convert a ISO format time to second
from:2006-04-12 16:46:40 to:23123123
把一個時間轉(zhuǎn)化為秒
'''
return time.strptime( s, ISOTIMEFORMAT )
def Time2ISOString( s ):
'''
convert second to a ISO format time
from: 23123123 to: 2006-04-12 16:46:40
把給定的秒轉(zhuǎn)化為定義的格式
'''
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是另外一個函數(shù),可以處理,3天,13分鐘,10小時等字符串,回頭再來寫這個,需要結(jié)合正則表達(dá)式。
'''
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 )