python3 獲取兩個時間戳相差多少天


 

code

import time
import datetime

t=datetime.datetime.now()

#當前日期
t1 =t.strftime('%Y-%m-%d %H:%M:%S')
#轉為秒級時間戳
ts1=time.mktime(time.strptime(t1, '%Y-%m-%d %H:%M:%S'))
#轉為毫秒級
end_time=int(str(ts1*1000).split(".")[0])


#48小時前
t2=(t-datetime.timedelta(hours=48)).strftime("%Y-%m-%d %H:%M:%S")
#轉為秒級時間戳
ts2=time.mktime(time.strptime(t2, '%Y-%m-%d %H:%M:%S'))
#轉為毫秒級
start_time=int(str(ts2*1000).split(".")[0])

print("\n","*"*30)

print(start_time)
print(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(ts2)))

print("*"*30)

print(end_time)
print(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(ts1)))

print("*"*30,"\n")

print("相差",(datetime.datetime.fromtimestamp(ts1)-datetime.datetime.fromtimestamp(ts2)).days,"")

outputs

macname@MacdeMBP Desktop % python3 test.py

 ******************************
1588754711000
2020-05-06 16:45:11
******************************
1588927511000
2020-05-08 16:45:11
****************************** 

相差 2 天
macname@MacdeMBP Desktop % 

 

 第二版本

import time
import datetime

t=datetime.datetime.now()

#當前時間
t1 =t.strftime('%Y-%m-%d %H:%M:%S')
#轉為秒級時間戳
second_timestamp1=time.mktime(time.strptime(t1, '%Y-%m-%d %H:%M:%S'))
#轉為毫秒級
microsecond_timestamp1=int(str(second_timestamp1*1000).split(".")[0])

#48小時前
t2=(t-datetime.timedelta(hours=48)).strftime("%Y-%m-%d %H:%M:%S")
#轉為秒級時間戳
second_timestamp2=time.mktime(time.strptime(t2, '%Y-%m-%d %H:%M:%S'))
#轉為毫秒級
microsecond_timestamp2=int(str(second_timestamp2*1000).split(".")[0])

print("\n","*"*30)

print("second_timestamp1:",second_timestamp1)
print("microsecond_timestamp1:",microsecond_timestamp1)
print(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(second_timestamp1)))

print("*"*30)

print("second_timestamp2:",second_timestamp2)
print("microsecond_timestamp2:",microsecond_timestamp2)
print(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(second_timestamp2)))

print("*"*30,"\n")

print("相差",(datetime.datetime.fromtimestamp(second_timestamp1)-datetime.datetime.fromtimestamp(second_timestamp2)).days,"")

outputs

macname@MacdeMBP Desktop % python3 test.py

 ******************************
second_timestamp1: 1588928019.0
microsecond_timestamp1: 1588928019000
2020-05-08 16:53:39
******************************
second_timestamp2: 1588755219.0
microsecond_timestamp2: 1588755219000
2020-05-06 16:53:39
****************************** 

相差 2 天
macname@MacdeMBP Desktop % 

 

 

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM