一.time模塊
1.import time
2.獲取時間戳
print(time.time())
獲取當前的格式化時間
Time=time.strftime()
二.時間戳和格式化時間的轉換(無論哪種轉哪種都得先轉成時間元祖)
1.時間元祖
print(time.gtime())#獲取到的是標准時區的時間
print(time.localtime())#獲取的是當前時區的時間
2.時間戳和格式化時間的轉換
時間戳轉為時間元祖:
s=time.localtime(time.time())
將時間元祖變為格式化時間
result=time.strftime('%Y-%m-%d %H:%M:%S',s)
三.將格式化的時間轉換為時間戳
M=time.strptime('2018-4-21','%Y-%m-%d')
time_stamp=time.mktime(M)
四.時間戳與格式化時間轉換,格式化好的時間轉換成時間戳, 封裝函數
1.時間戳與格式化時間轉換,函數封裝
def timestamp_to_format(timestamp=None,format='%Y-%m-%d %H:%M:%S'):
if timestamp:
time_tuple=time.localtime(timestamp)
res=time.strftime(format,time_tuple)
else:
res=time.strftime(format)
return res
res=timestamp_to_format()
res=timestamp_to_format('1990101202',%Y-%m)
2.將格式化好的時間轉為時間戳,並封裝函數
def str_to_timestamp(str=None,format='%Y%m%d%H%M%S'):
if str:
tp=time.strptime(str,format)--轉成時間元祖
res=time.mktime(tp)
else:
res=time.time()
return int(res)