下面是測試代碼:python
#coding:utf-8 ''' base on python 2.7 Created on 2012-12-14 @author: yiahomen.com ''' import datetime import time def datetime_toString(dt): """把datetime轉成字符串""" return dt.strftime("%Y-%m-%d") def string_toDatetime(string): """把字符串轉成datetime""" return datetime.datetime.strptime(string, "%Y-%m-%d") def string_toTimestamp(strTime): """把字符串轉成時間戳形式""" return time.mktime(string_toDatetime(strTime).timetuple()) def timestamp_toString(stamp): """把時間戳轉成字符串形式""" return time.strftime("%Y-%m-%d-%H", time.localtime(stamp)) def datetime_toTimestamp(dateTime): """把datetime類型轉外時間戳形式""" return time.mktime(dateTime.timetuple()) def substract_DateTime(dateStr1,dateStr2): """ 返回兩個日期之間的差 """ d1=string_toDatetime(dateStr1) d2=string_toDatetime(dateStr2) return d2-d1 def substract_TimeStamp(dateStr1,dateStr2): """ 兩個日期的 timestamp 差值 """ ts1= string_toTimestamp(dateStr1) ts2= string_toTimestamp(dateStr2) return ts1-ts2 def compare_dateTime(dateStr1,dateStr2): """兩個日期的比較, 固然也能夠用timestamep方法比較,均可以實現.""" date1 = string_toDatetime(dateStr1) date2 = string_toDatetime(dateStr2) return date1.date()>date2.date() def dateTime_Add(dateStr,days=0,hours=0,minutes=0): """ 指定日期加上 一個時間段,天,小時,或分鐘以後的日期 """ date1= string_toDatetime(dateStr) return date1+datetime.timedelta(days=days,hours=hours,minutes=minutes) if __name__=='__main__': print substract_DateTime('2012-12-12','2012-01-01') #-346 days, 0:00:00 print substract_DateTime('2012-12-12','2012-01-01').days #-346 print substract_TimeStamp('2012-12-12','2012-01-01') #29894400.0 print substract_TimeStamp('2012-12-12','2012-01-01')/(24*60*60),'天' #346.0 天 print compare_dateTime('2012-12-12','2012-01-01') #True print dateTime_Add('2012-12-12',days=10,hours=5,minutes=10) #2012-12-22 05:10:00