一、time模塊
time模塊中時間表現的格式主要有三種:
a、timestamp時間戳,時間戳表示的是從1970年1月1日00:00:00開始按秒計算的偏移量
b、struct_time時間元組,共有九個元素組。
c、format time 格式化時間,已格式化的結構使時間更具可讀性。包括自定義格式和固定格式。
時間格式轉換圖:
import time,datetime
time.localtime() # 返回本地時間 的struct time對象格式
time.gmtime() # 返回utc 的struct time對象格式
#不寫參數表示返回當前的struct time對象,輸入一個時間戳參數:time.localtime(string_2_stamp) 時間戳--> 時間對象
time.asctime(time.localtime()) #接收struct time對象參數
time.ctime()
#返回"Fri Aug 19 11:14:16 2016"時間格式
#日期字符串--> 時間戳
s="2017/3/24 20:47"
string_2_struct=time.strptime(s,"%Y/%m/%d %H:%M") #日期字符串--> 時間對象
print(string_2_struct)
string_2_stamp=time.mktime(string_2_struct) #時間對象--> 時間戳
print(string_2_stamp)
#時間戳--> 字符串
t1=time.localtime(string_2_stamp) #時間戳--> 時間對象
t1_2_string=time.strftime("%Y_%m_%d_%H_%M",t1) #時間對象--> 字符串
print(t1_2_string)
二、datetime模塊
datatime模塊重新封裝了time模塊,提供更多接口,提供的類有:date,time,datetime,timedelta,tzinfo。
時間加減
datetime.datetime.now() #返回當前本地時間的datetime對象
datetime.fromtimestamp(time_stamp) #時間戳轉化成datetime對象
print(datetime.datetime.now()+datetime.timedelta(days=3)) #當前時間+3天
print(datetime.datetime.now()+datetime.timedelta(-3)) #當前時間-3天
print(datetime.datetime.now()+datetime.timedelta(minutes=30)) #當前時間+30分鐘
時間表現類型轉換(和time模塊一樣)
datetime.datetime.fromtimestamp(time.time()) #時間戳 --> datetime對象
datetime.datetime.timestamp(datetime_struct) #datetime對象--> 時間戳
#字符串 --> 時間戳
s="2017/4/1 19:03:22"
string_2_struct=datetime.datetime.strptime(s,"%Y/%m/%d %H:%M:%S") #日期字符串--> datetime對象
stamp=datetime.datetime.timestamp(string_2_struct)
print(stamp)
#時間戳--> 字符串
t=datetime.datetime.fromtimestamp(stamp)
t_2_string=stamp=datetime.datetime.strftime(t,"%Y_%m_%d_%H_%M_%S") #datetime對象--> 日期字符串
print(t_2_string)
時間替換
c_time=datetime.datetime.now()
print(c_time)
print(c_time.replace(hour=2,minute=3))