【整理】Python中字串與時間的轉換與計算
來源:互聯網
上載者:User
一、string time datetime之間的相互轉換
1、string->time>>> time.strptime('2012-08-04', '%Y-%m-%d')
time.struct_time(tm_year=2012, tm_mon=8, tm_mday=4, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=5, tm_yday=217, tm_isdst=-1)
2、time->string>>> import time#方法1
>>> time.strftime('%Y-%m-%d', time.localtime()) #'2012-08-04'#方法2
>>> time.strftime('%Y-%m-%d', time.localtime(time.time())) #'2012-08-04'其中strftime(應該是string format time的意思)用來格式化時間,第一個參數為格式化字串,第二個參數為一個結構體struct,而time.time()函數則是擷取機器時間
3、string -> datetime#方法1按string->time->datetime進行轉化>>> import datetime
>>> datetime.datetime(
*time.strptime('2012-08-04', '%Y-%m-%d')[:3]) #datetime.datetime(2012, 8, 4, 0, 0)#方法2>>> import datetime>>> datetime.datetime.strptime('2012-08-04', '%Y-%m-%d') #datetime.datetime(2012, 8, 4, 0, 0)
4、datetime -> string >>> import datetime>>> now = time.localtime()>>> dt = datetime.datetime(*now[:3])#按指定的格式返回字串>>> dt.strftime(format='%Y-%m-%d') #'2012-08-04'#預設格式返回字串>>> dt.ctime() #'Sat Aug 4 00:00:00 2012'
5、time -> datetime>>> import datetime
>>> now = time.localtime()>>> datetime.datetime(*now[:3]) #datetime.datetime(2012, 8, 4, 0, 0)
6、datetime -> time>>> dt.timetuple()
輸出:time.struct_time(tm_year=2012, tm_mon=8, tm_mday=4, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=5, tm_yday=217, tm_isdst=-1)
二、datetime的計算datetime的加減會涉及timedelta
1、時間相減>>> dt1 = datetime.datetime(2012, 8, 4, 20, 33, 34)
>>> dt2 = datetime.datetime(2012, 7, 5, 14, 22, 32)
>>> dt1-dt2 #datetime.timedelta(30, 22262)>>> (dt1-dt2).days #30
2、一段時間之後或之前>>> dt1+datetime.timedelta(days=10) #datetime.datetime(2012, 8, 14, 20, 33, 34)>>> dt1-datetime.timedelta(days=10) #datetime.datetime(2012, 7, 25, 20, 33, 34)>>> dt4 = datetime.date(2012, 8, 14)
>>> dt5 = datetime.date(2012, 7, 22)
>>> dt4-dt5 #datetime.timedelta(23)