Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
527 views
in Technique[技术] by (71.8m points)

python - Difference between two unix timestamps

I have two timestamps in miliseconds and i want to compute the difference between the two in minutes:

d1 = 1502053449617 

current_time_utc = int(round(time.time() * 1000))

The values for d1 are dynamically generated by a third party API and are in UTC . I am trying to get the difference between the current time in UTC and d1.

fmt = '%Y-%m-%d %H:%M:%S'

 time1  = datetime.strptime(d1, fmt)
 time2  = datetime.strptime(current_time_utc, fmt)

I want to be able to find the difference between the two (time1 - time2) . If i do the below , i get an error saying "string expected, long given"

print(    time1-time2)

I want the difference between the two in minutes . Please help

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You don't need to format the string, you just need to convert the timestamp directly, by first dividing it by 1000. Then its just a matter of printing out the differences (and calculating it in minutes):

from __future__ import division
import datetime

d1 = 1502053449617

converted_d1 = datetime.datetime.fromtimestamp(round(d1 / 1000))
current_time_utc = datetime.datetime.utcnow()

print((current_time_utc - converted_d1))
print((current_time_utc - converted_d1).total_seconds() / 60)

The above prints:

3 days, 5:08:14.087515
4628.234791916667

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...