Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Sum up Time difference
#1
Greetings!
I’m calculating the time difference between some start and finish time stamps and need to sum up the outcome for each file.
Here is a snipped that gets the time difference:
t_end = datetime.strptime(end_t, "%m/%d/%Y %I:%M:%S %p")                    
t_start = datetime.strptime(start_t, "%m/%d/%Y %I:%M:%S %p")
time_dif = t_end - t_start
print(f" Time Difference = {time_dif}-{type(time_dif)}")
And the printout:
START TIME = 4/3/2023 4:12:17 PM
 END TIME = 4/3/2023 4:13:50 PM
 Time Difference  = 0:01:33-<class 'datetime.timedelta'>
 START TIME = 4/3/2023 4:15:12 PM
 END TIME = 4/3/2023 4:16:17 PM
 Time Difference  = 0:01:05-<class 'datetime.timedelta'>
 START TIME = 4/3/2023 4:17:02 PM
 END TIME = 4/3/2023 4:18:07 PM
 Time Difference  = 0:01:05-<class 'datetime.timedelta'>
 START TIME = 4/3/2023 4:18:57 PM
 END TIME = 4/3/2023 4:20:02 PM
 Time Difference  = 0:01:05-<class 'datetime.timedelta'>
 START TIME = 4/3/2023 4:24:06 PM
 END TIME = 4/3/2023 4:25:08 PM
 Time Difference  = 0:01:02-<class 'datetime.timedelta'>
I’d like to sum up the “time Difference”. I could convert it to seconds and then sum it up, and convert seconds to HHMMSS after that but I was wondering if I could do it in a better way.

Thank you!
Reply
#2
Why not sum the timedelta instances?
>>> from datetime import timedelta
>>> d = [timedelta(seconds=1), timedelta(seconds=5), timedelta(seconds=7)]
>>> d
[datetime.timedelta(seconds=1), datetime.timedelta(seconds=5), datetime.timedelta(seconds=7)]
>>> sum(d, timedelta(seconds=0))
datetime.timedelta(seconds=13)
ibreeden and tester_V like this post
Reply
#3
Gribouillis, if I understand you correctly I have to convert "Time Difference = 0:01:05-<class 'datetime.timedelta'>" to seconds, append it to a list, and sum up the list items. Right?

Thank you.
Reply
#4
Did you try to sum timedelta objects? I would assume you can sum objects if the objects can be added. You can add timedelta objects.

https://docs.python.org/3/library/dateti....timedelta

Pay close attention to what Gribouillis did. In particular this:
sum(d, timedelta(seconds=0))
Why do you think there is a timedelta(seconds=0) after the list of times? Isn't that 0 seconds? Why is that there? Maybe looking at the documentation for sum will clear things up.

https://docs.python.org/3/library/functions.html#sum
tester_V likes this post
Reply
#5
(Apr-05-2023, 05:15 AM)tester_V Wrote: I’d like to sum up the “time Difference”. I could convert it to seconds and then sum it up
The converting to seconds is already done,just that you use print() will not see the repr() datetime response.
You code.
from datetime import datetime

start_t = '4/3/2023 4:12:17 PM'
end_t = '4/3/2023 4:13:50 PM'

t_end = datetime.strptime(end_t, "%m/%d/%Y %I:%M:%S %p")
t_start = datetime.strptime(start_t, "%m/%d/%Y %I:%M:%S %p")
time_dif = t_end - t_start
See that is show 93 sec.
>>> time_dif
datetime.timedelta(seconds=93)
>>> 
>>> print(f" Time Difference = {time_dif}-{type(time_dif)}")
 Time Difference = 0:01:33-<class 'datetime.timedelta'>
So can just easily add up.
>>> new = time_dif + time_dif
>>> new
datetime.timedelta(seconds=186)
>>> 
>>> print(f"Time Difference = {new}")
Time Difference = 0:03:06
tester_V likes this post
Reply
#6
(Apr-05-2023, 06:04 PM)tester_V Wrote: Gribouillis, if I understand you correctly I have to convert "Time Difference = 0:01:05-<class 'datetime.timedelta'>" to seconds, append it to a list, and sum up the list items. Right?
You should never do what you say. It can give the wrong result.
from datetime import timedelta

x = timedelta(days=1), timedelta(days=1)
total = sum(a.seconds for a in x)
print(total)
Output:
0
This should be 2 * 24 * 60 * 60 seconds, right? The reason it is not has to do with what seconds mean in timedelta.
Quote:Only days, seconds and microseconds are stored internally. Arguments are converted to those units:

A millisecond is converted to 1000 microseconds.

A minute is converted to 60 seconds.

An hour is converted to 3600 seconds.

A week is converted to 7 days.
Internally, timedelta objects have microseconds, seconds, and days. These are independent values. In the example above, the timedelta is 1 day, 0 seconds, 0 microseconds. When I ask for the number of seconds it returns 0, the number of seconds in the seconds attribute of the timedelta object. This is not the same as the duration measured in seconds. To get that use total_seconds()
Quote:timedelta.total_seconds()
Return the total number of seconds contained in the duration. Equivalent to td / timedelta(seconds=1). For interval units other than seconds, use the division form directly (e.g. td / timedelta(microseconds=1)).

Note that for very large time intervals (greater than 270 years on most platforms) this method will lose microsecond accuracy
from datetime import timedelta

x = timedelta(days=1), timedelta(days=1)
total = sum(a.total_seconds() for a in x)
print(total)
Output:
172800.0
tester_V likes this post
Reply
#7
(Apr-05-2023, 06:34 PM)deanhystad Wrote: Did you try to sum timedelta objects? I would assume you can sum objects if the objects can be added. You can add timedelta objects.

https://docs.python.org/3/library/dateti....timedelta

Pay close attention to what Gribouillis did. In particular this:
sum(d, timedelta(seconds=0))
Why do you think there is a timedelta(seconds=0) after the list of times? Isn't that 0 seconds? Why is that there? Maybe looking at the documentation for sum will clear things up.

https://docs.python.org/3/library/functions.html#sum
I kind of understand the idea but I do not see how I can use it with the time delta I have as "Time Difference = 0:08:13-<class 'datetime.timedelta'>"
It makes me sad Confused but we are not on the same Python planet yet brother....
Need to put more work into it.

Thank you!
Reply
#8
Did you read the sum documentation? I provided a link.

Quote:sum(iterable, /, start=0)
Sums start and the items of an iterable from left to right and returns the total. The iterable’s items are normally numbers, and the start value is not allowed to be a string.

I try a test to see if it works. I'm going to make a list of timedelta objects and sum them up.
from datetime import timedelta

deltas = [timedelta(hours=1, minutes=59, seconds=59) for _ in range(10)]

print(sum(deltas))
Error:
Traceback (most recent call last): File "...test.py", line 5, in <module> print(sum(deltas)) TypeError: unsupported operand type(s) for +: 'int' and 'datetime.timedelta'
Does this mean I cannot use sum() with timedelta objects? A closer look at the error message reveals the problem.
Quote:Unsupported types for +: int and timedelta.
I see the timedelta objects, but where is the int?

The int is here:
Quote:sum(iterable, /, start=0)
The result of sum is "start" and items from the iterable. I did not provide a "start" argument, so it uses the default value: 0. 0 is an int, and we cannot add an int and a timedelta object.

To correct we need to provide a "start" argument that is a timedelta object. We don't want the start to change the sum, so we want the timedelta equivalent of 0.
from datetime import timedelta

deltas = [timedelta(hours=1, minutes=35, seconds=42) for _ in range(10)]

print(sum(deltas, timedelta(seconds=0)))
Output:
19:59:50
If we are from different worlds, they are the world of "Reading the documentation" and "Not reading the documentation". You need to hop on a rocket and travel to the world of "Reading the documentation". It can be difficult at first, but I think it results in a deeper understanding than looking for matching examples only. You'll like it. It is very nice.
tester_V likes this post
Reply
#9
You guys did your best, I'm sure it all makes sens but not for my level of understanding..
Sorry about that!
I do not see how I can get from this:
 START TIME = 4/3/2023 4:18:57 PM
 END TIME = 4/3/2023 4:20:02 PM
 Time Difference  = 0:01:05-<class 'datetime.timedelta'>
 START TIME = 4/3/2023 4:24:06 PM
 END TIME = 4/3/2023 4:25:08 PM
 Time Difference  = 0:01:02-<class 'datetime.timedelta'>
to this:
deltas = [timedelta(hours=1, minutes=35, seconds=42) for _ in range(10)]
 
print(sum(deltas, timedelta(seconds=0)))
or to this:
x = timedelta(days=1), timedelta(days=1)
total = sum(a.total_seconds() for a in x)
print(total)
this is complicated... And I really appreciate your help!

Thank you guys, you are the best, I'll get it someday.
Reply
#10
I have a "test.txt" file that looks like this:
Output:
START TIME = 4/3/2023 4:12:17 PM END TIME = 4/3/2023 4:13:50 PM START TIME = 4/3/2023 4:15:12 PM END TIME = 4/3/2023 4:16:17 PM START TIME = 4/3/2023 4:17:02 PM END TIME = 4/3/2023 4:18:07 PM START TIME = 4/3/2023 4:18:57 PM END TIME = 4/3/2023 4:20:02 PM START TIME = 4/3/2023 4:24:06 PM END TIME = 4/3/2023 4:25:08 PM
I want to go through and file and sum up the times between START and END times. Some of this code will look familiar.
from datetime import datetime, timedelta

format = "%m/%d/%Y %I:%M:%S %p"
diffs = []

with open("test.txt", "r") as file:
    for line in file:
        if line.startswith("START TIME = "):
            datetime_str = line.split("=")[1].strip()
            start_time = datetime.strptime(datetime_str, format)
        elif line.startswith("END TIME = "):
            datetime_str = line.split("=")[1].strip()
            end_time = datetime.strptime(datetime_str, format)
            diffs.append(end_time - start_time)

print("Time Deltas", *diffs, sep="\n")

total = sum(diffs, timedelta(seconds=0))
print("Total", total)
Output:
Time Deltas 0:01:33 0:01:05 0:01:05 0:01:05 0:01:02 Total 0:05:50
Of you could forget about using sum() and keep a running total.
from datetime import datetime, timedelta

format = "%m/%d/%Y %I:%M:%S %p"
total = timedelta(seconds=0)

with open("test.txt", "r") as file:
    start_time = None
    end_time = None
    for line in file:
        if line.startswith("START TIME = "):
            datetime_str = line.split("=")[1].strip()
            start_time = datetime.strptime(datetime_str, format)
        elif line.startswith("END TIME = "):
            datetime_str = line.split("=")[1].strip()
            end_time = datetime.strptime(datetime_str, format)
            delta = end_time - start_time
            total += delta
            print(end_time, "-", start_time, "=", delta)

print("Total", total)
Output:
2023-04-03 16:13:50 - 2023-04-03 16:12:17 = 0:01:33 2023-04-03 16:16:17 - 2023-04-03 16:15:12 = 0:01:05 2023-04-03 16:18:07 - 2023-04-03 16:17:02 = 0:01:05 2023-04-03 16:20:02 - 2023-04-03 16:18:57 = 0:01:05 2023-04-03 16:25:08 - 2023-04-03 16:24:06 = 0:01:02 Total 0:05:50
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  time difference bettwenn logs enkliy 14 992 Nov-21-2023, 04:51 PM
Last Post: rob101
  Hard time trying to figure out the difference between two strings carecavoador 2 679 Aug-16-2023, 04:53 PM
Last Post: carecavoador
  How to get indices of minimum time difference Mekala 1 2,159 Nov-10-2020, 11:09 PM
Last Post: deanhystad
  How to calculate time difference between each row of dataframe in seconds Mekala 1 2,579 Jul-16-2020, 12:57 PM
Last Post: Larz60+
  Correlation of Incidents using time difference Rajhesh 1 1,828 Jun-27-2019, 03:44 PM
Last Post: Larz60+
  Time Difference in Epoch Microseconds then convert to human readable firesh 4 11,629 Feb-27-2018, 09:08 AM
Last Post: firesh
  Calculating time difference between times and splitting the HH and MM Bass 7 10,645 Jul-03-2017, 01:26 PM
Last Post: Bass

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020