在寫腳本或者網站返回數據時候,常常遇到須要講時間轉換成不一樣格式的狀況,這裏我總結下本身遇到的需求以及解決辦法。數據庫
首先咱們須要瞭解一下幾個表達:數組
(1)時間戳bash
>>> import time >>> time.time() #時間戳 帶毫秒 1465867278.111247 >>> int(time.time()) 1465867395 #時間戳 整秒
(2)時間數組網站
>>> time.localtime(1455874589.054742) time.struct_time(tm_year=2016, tm_mon=2, tm_mday=19, tm_hour=17, tm_min=36, tm_sec=29, tm_wday=4, tm_yday=50, tm_isdst=0)
>>> a = "2016-01-16 06:42:09" >>> time.strptime(a, "%Y-%m-%d %H:%M:%S") time.struct_time(tm_year=2016, tm_mon=1, tm_mday=16, tm_hour=6, tm_min=42, tm_sec=9, tm_wday=5, tm_yday=16, tm_isdst=-1)
(3)時間格式spa
>>> import datetime >>> datetime.datetime.now() datetime.datetime(2016, 6, 14, 9, 30, 39, 7797) >>> print datetime.datetime.now() 2016-06-14 09:30:46.535643
上面三種,咱們用到最多的就是(1)時間戳和(3)時間格式,code
時間戳用於數據庫存儲,在執行腳本的時候計算時間間隔等都很是方便,class
時間格式用於網站上顯示時間很直觀。import
------------date
(1)時間格式 --> 時間戳im
>>> import time,datetime >>> a = '2016-01-16 06:42:09' #後面沒有毫秒 >>> b = time.mktime(time.strptime(a, '%Y-%m-%d %H:%M:%S')) >>> b 1452897729.0 >>> a = '20160630' >>> b = time.mktime(time.strptime(a, "%Y%m%d")) >>> b 1467216000.0
>>> import time, datetime >>> now = datetime.datetime.now() >>> a = time.mktime(now.timetuple()) >>> a 1465870113.0
(2)時間戳 --> 時間格式
>>> import time, datetime >>> timeStamp = time.time() >>> dateArray = datetime.datetime.utcfromtimestamp(timeStamp) >>> StyleTime = dateArray.strftime("%Y-%m-%d %H:%M:%S.%f") >>> StyleTime '2016-06-14 01:57:28.172960'
(3)時間格式中 時間值 的替換
>>> datetime.datetime.now().replace(year=2000,month=1, day=1,hour=0, minute=0, second=0, microsecond=0) datetime.datetime(2000, 1, 1, 0, 0) >>> str(datetime.datetime.now().replace(year=2000,month=1, day=1,hour=0, minute=0, second=0, microsecond=0)) '2000-01-01 00:00:00'
(4)計算出固定時間的時間戳
>>> a = datetime.datetime.now().replace(month=1, day=1,hour=0, minute=0, second=0, microsecond=0) >>> b = time.mktime(a.timetuple()) >>> b 1451577600.0
(5)計算前9天的時間
>>> datetime.datetime.now() datetime.datetime(2016, 6, 14, 10, 45, 4, 798335) >>> datetime.datetime.now() - datetime.timedelta(days=9) datetime.datetime(2016, 6, 5, 10, 45, 26, 573241)
(6)時間格式轉換爲其餘指定格式
>>> a = '2016-01-16 06:42:09' >>> timeArray = time.strptime(a, "%Y-%m-%d %H:%M:%S") >>> otherStyleTime = time.strftime("%Y/%m/%d %H:%M:%S", timeArray) >>> otherStyleTime '2016/01/16 06:42:09'