一、Time模塊
(1)time.time()輸出當前時間戳
# -*- coding: UTF-8 -*- import time; # 引入time模塊 ticks = time.time() print "當前時間戳為:", ticks 輸出 當前時間戳為: 1459994552.51
(2)獲取當前時間,時間元組的形式localtime()
localtime = time.localtime(time.time()) print "本地時間為 :", localtime 輸出結果: 本地時間為 : time.struct_time(tm_year=2016, tm_mon=4, tm_mday=7, tm_hour=10, tm_min=3, tm_sec=27, tm_wday=3, tm_yday=98, tm_isdst=0)
(3)最簡單的獲取可讀的時間形式asctime():
localtime = time.asctime( time.localtime(time.time()) ) print "本地時間為 :", localtime 輸出結果: 本地時間為 : Thu Apr 7 10:05:21 2016
(4)格式化日期
time.strftime(format[, t]),如果t未指定默認傳入,默認time.localtime()
# 格式化成2016-03-20 11:45:39形式 print time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) #或者直接time.strftime("%Y-%m-%d %H:%M:%S")
# 格式化成Sat Mar 28 22:24:24 2016形式 print time.strftime("%a %b %d %H:%M:%S %Y", time.localtime()) # 將格式字符串轉換為時間戳 a = "Sat Mar 28 22:24:24 2016" print time.mktime(time.strptime(a,"%a %b %d %H:%M:%S %Y"))
輸出結果
2016-04-07 10:25:09 Thu Apr 07 10:25:09 2016 1459175064.0


小結:
time模塊中時間表現的格式主要有3種:
1. timestamp 時間戳
2. tuple或者struct_time 時間元組,共有九個元素組
3. formattime格式化字符串

(5)time.sleep(60) 推遲調用線程的運行,60s
二、datetime模塊
(1)獲取當前時間和日期
import datetime
print(datetime.datetime.today())
print(datetime.datetime.now())
2018-08-14 22:24:23.022380
2018-08-14 22:24:23.022380
(2)獲取指定日期
>>> from datetime import datetime >>> dt = datetime(2015, 4, 19, 12, 20) # 用指定日期時間創建datetime >>> print(dt) 2015-04-19 12:20:00
(3)datetime轉換為timestamp
>>> from datetime import datetime >>> dt = datetime(2015, 4, 19, 12, 20) # 用指定日期時間創建datetime >>> dt.timestamp() # 把datetime轉換為timestamp 1429417200.0
(4)timestamp轉換為datetime
>>> from datetime import datetime >>> t = 1429417200.0 >>> print(datetime.fromtimestamp(t)) 2015-04-19 12:20:00
(5)str轉換為datetime
>>> from datetime import datetime >>> cday = datetime.strptime('2015-6-1 18:19:59', '%Y-%m-%d %H:%M:%S') >>> print(cday) 2015-06-01 18:19:59
(6)datetime轉換為str
>>> from datetime import datetime >>> now = datetime.now() >>> print(now.strftime('%a, %b %d %H:%M')) Mon, May 05 16:28
(7)datetime加減
加減可以直接用+和-運算符,不過需要導入timedelta這個類:
>>> from datetime import datetime, timedelta >>> now = datetime.now() >>> now datetime.datetime(2015, 5, 18, 16, 57, 3, 540997) >>> now + timedelta(hours=10) datetime.datetime(2015, 5, 19, 2, 57, 3, 540997) >>> now - timedelta(days=1) datetime.datetime(2015, 5, 17, 16, 57, 3, 540997) >>> now + timedelta(days=2, hours=12) datetime.datetime(2015, 5, 21, 4, 57, 3, 540997)
參考:
