time包
time包的基礎型別是struct_time。
time.sleep() 讓程式 延時,以秒為單位。
time.time() 返回時間戳,浮點型。
time.strptime(string, format)
用法 ,將字串轉換成 struct_time,返回時間結構struct_time
time_struct = time.strptime('2014-10-10 22:22:12',"%y-%m-%d %h:%m:%s")time.strftime(format,
struct_time)
用法,struct_time
將轉換成
字串, 返回字串。
time.strftime(time.mktime(time_struct)"%y-%m-%d",struct_time)
如果是將當前時間轉化成字串 用 time.strftime(
"%y-%m-%d %h:%m:%s",time.localtime())
用法,時間結構到時間戳,返回浮點形式的 時間戳。
time.gmtime(time_stamp)
用法,將時間戳,轉化成時間結構,返回時間結構。
time.gmtime(1812950932)time.localtime()
用法,將時間戳,轉化成時間結構,返回時間結構。
time.localtime()gmtime()和loaltime() 都是將 時間戳 轉換成 時間結構 ,不同之處是 gmtime 轉化成 格林威治時間, localtime 轉換出來的是當地時間,比如我們就是北京時間。 所以一般time.localtime() 括號裡都不加引數,預設就是取得當前的時間戳,轉換成當前時間。
總結
字串 到 time_struct 用 time.strptime()
time_struct 到 字串 用 time.strftime()
時間戳 到 time_struct 用 time.gmtime(time_stamp) 或者 time.
localtime
(time_stamp) time_stamp可以省略
time_struct 到 時間戳 用 time.mktime(time_struct)
可以看到 字串 和 時間戳之間 沒有 直接轉換的關係 ,可以通過 時間結構 來作為 過渡。
簡圖:
雖然 time.ctime() 也是 將 時間戳 轉化為 字串,但是不能用 格式化字元 來定製,用處有限。如
time.ctime(1212950932) 的 返回結果 是 mon jun 9 02:48:52 2008 。
time.asctime(time_struct) 也是將 時間結構體 ,轉化成 字串,通ctime一樣,生成的字串格式,不能定製。如
time.asctime(time_struct) 的返回結果是 mon jun 14 05:28:52 2027。
資料庫中的型別如果是datetime,用timetuple()方法可以轉化為time_struct型別。如
kaifu_date.timetuple()
時間偏移
new_date = olddate + datetime.timedelta(seconds=-1)
表示一天前的 字串
now = datetime.datetime.now()
now =
time.strftime(
"%y-%m-%d %h:%m:%s",time.localtime())
yesterday = now - datetime.timedelta(days=1)
print time.strftime("%y-%m-%d",yesterday.timetuple())
mysql 中取出來的時間型別 轉換 到 時間戳
time.mktime(update_time.timetuple())
python time時間模組
想讓程式停頓幾秒鐘 time.sleep 秒數 例如 print 1 time.sleep 2 print 2 結果,在列印了1後會停2秒,然後再列印2 三種時間格式 時間戳,是計算機可識別的乙個時間形態 格式化時間字串,是人類可識別的乙個時間形態 時間元組,則是二個時間的過渡體 可以把這三者間的關...
Python time 時間模組
time 模組提供各種時間相關的功能 在 python 中,與時間處理有關的模組包括 time,datetime 以及 calendar import time 該模組方法中包含三種時間的形式 時間戳 元組時間 字串時間 時間形式的轉換 t time.time 取當前時間的 時間戳 tt time....
python Time(時間)模組
要使用乙個模組,首先要把模組匯入進來 import time 我們先把這一篇文章需要用的模組匯入進來 首先說一下time模組,time模組中的函式 sleep 休眠指定的秒數 可以是小數 import time print 開始 time.sleep 5 print 結束 如果在pycharm中輸入...