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