简体   繁体   中英

Find time difference between 2 time stamp values in python

import datetime

def get_time_value(timestamp):
     time = datetime.datetime.fromtimestamp(timestamp)
     return time.strftime("%Y-%m-%d %H:%M:%S")

I have

start_time = 1518842893.04001
end_time = 1518842898.21265

get_time_value(end_time-start_time)

It gives

1969-12-31 16:00:05

and not the correct value

'startTime': '2018-02-16 20:48:13', 'endTime': '2018-02-16 20:48:18'

To get the time difference between two timestamps, first convert them to datetime objects before the subtraction. If you do this then the result will be a datetime.timedelta object. Once you have a datetime.timedelta object you can convert it to seconds or however you want to display the time difference.

For example.

time1 = datetime.datetime.fromtimestamp(start_time)
time2 = datetime.datetime.fromtimestamp(end_time)
time_difference = time2 - time1
print(time_difference)

Output:

0:00:05.172640

Or:

print(time_difference.total_seconds())

Output:

5.17264

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM