1
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'
user544079
  • 16,109
  • 42
  • 115
  • 171
  • 1
    Possible duplicate of [How to calculate the time interval between two time strings](https://stackoverflow.com/questions/3096953/how-to-calculate-the-time-interval-between-two-time-strings) – Mark Schultheiss Feb 17 '18 at 05:18
  • Your 'correct value' looks like a dictionary containing the start and end times but without curly-braces. Is this really what you want? The title of the post says that you want the time difference between the 2 time stamp values. – Bill Feb 17 '18 at 05:33
  • Possible duplicate of [Python - Date & Time Comparison using timestamps, timedelta](https://stackoverflow.com/questions/12131766/python-date-time-comparison-using-timestamps-timedelta) – Bill Feb 17 '18 at 05:45

1 Answers1

1

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
Bill
  • 10,323
  • 10
  • 62
  • 85
  • And how is that any better than just doing `end_time-start_time`? This is just a pointless conversion into datetime instances and then back again. – wim Feb 17 '18 at 06:52
  • Good point. I admit I still don't know what you mean by "Find time difference between 2 time stamp values in python" Can you show the output you want to produce? – Bill Feb 17 '18 at 07:05