from datetime import datetime
print(datetime.now()) 本地時間
print(datetime.utcnow()) 國際時間
time
#13位或10位時間戳轉正常時間。
import time
def timestamp_to_normal_time(timestamp):
timestamp=str(timestamp)
if len(timestamp)==13:
timestamp_10=int(timestamp)/1000
elif len(timestamp)==10:
timestamp_10=int(timestamp)
else:
return None
time_array=time.localtime(timestamp_10)
normal_time = time.strftime("%Y-%m-%d %H:%M:%S", time_array)
return normal_time
datetime
import datetime
def timestamp_to_normal_time(timestamp):
timestamp=str(timestamp)
if len(timestamp)==13:
timestamp_10=int(timestamp)/1000
elif len(timestamp)==10:
timestamp_10=int(timestamp)
else:
return None
time_array=datetime.datetime.fromtimestamp(timestamp_10)
normal_time = time.strftime("%Y-%m-%d %H:%M:%S", time_array)
return normal_time
獲取時間戳
#10位,秒級
import time
t=int(round(time.time()))
print(t)
>>> 1558769924
#13位,毫秒級,round()函數是四舍五入。
t13=round(time.time()*1000)
print(t13)
>>>1558769647825
#計算時間差
def cal_difftime(date1, date2):
if is_date(date1) and is_date(date2):
date3=datetime.strptime(date1,"%Y-%m-%d %H:%M:%S") # 字符串轉換為datetime類型
date4=datetime.strptime(date2,"%Y-%m-%d %H:%M:%S") # 字符串轉換為datetime類型
times = str(date4 - date3).split(':')
difftime = times[0]+'時'+times[1]+'分'+times[2]+'秒'
return difftime
#判斷日期是否為合法輸入,年月日的格式需要與上面對應,正確返回True,錯誤返回False,注意大小寫。
def is_date(date):
try:
datetime.strptime(date,"%Y-%m-%d %H:%M:%S")
return True
except:
return False