Python Forum
Need to sum up HHMMS AM/PM DD/MM/YYYY and a HH:MM:SS. - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Need to sum up HHMMS AM/PM DD/MM/YYYY and a HH:MM:SS. (/thread-39118.html)



Need to sum up HHMMS AM/PM DD/MM/YYYY and a HH:MM:SS. - tester_V - Jan-04-2023

Greetings!
I have a time string, it shows the time something started running:
08:31:27 PM 01/02/2023
And the total 'HH:MM:SS' it took to finish the run:
01:22:14
I need to create the ‘finished running’ string by adding the HH:MM:SS to the 08:31:27 PM 01/02/2023.

Should I split the ‘start string’, get the hh:mm:ss, and convert that to total seconds?
Then convert to seconds the “finish run” to seconds.
Sum up both seconds, convert the total seconds to HH:MM:SS, and add the Date time to that.
All of it would look like this:
08:31:27 PM 01/02/2023, 09:53:41 27 PM 01/02/2023

It will work but I do not like how it looks, kind of ugly… Sad
Any thoughts on this?
Thank you.


RE: Need to sum up HHMMS AM/PM DD/MM/YYYY and a HH:MM:SS. - Yoriz - Jan-04-2023

Using datetime
import datetime


start_string = "08:31:27 PM 01/02/2023"
total_time_string = "01:22:14"
format_string = "%I:%M:%S %p %d/%m/%Y"
start_datetime = datetime.datetime.strptime(start_string, format_string)
hours, minutes, seconds = total_time_string.split(":")
total_timedelta = datetime.timedelta(
    hours=float(hours), minutes=float(minutes), seconds=float(seconds)
)
end_datetime = start_datetime + total_timedelta
print(
    f"{start_datetime.strftime(format_string)}, {end_datetime.strftime(format_string)}"
)
Output:
08:31:27 PM 01/02/2023, 09:53:41 PM 01/02/2023



RE: Need to sum up HHMMS AM/PM DD/MM/YYYY and a HH:MM:SS. - deanhystad - Jan-04-2023

If you are measuring your runtime in seconds it might make more sense using datetime.fromtimestamp()
from datetime import datetime

now = datetime.now().timestamp()
runtime = 1 * 3600 + 22 * 60 + 14  # 1:22:14 seconds

print(datetime.fromtimestamp(now))
print(datetime.fromtimestamp(now + runtime))
Output:
2023-01-04 14:52:30.891579 2023-01-04 16:14:44.891579
If your runtime is a HH:MM:SS string, Yoriz's solution is a better choice.


RE: Need to sum up HHMMS AM/PM DD/MM/YYYY and a HH:MM:SS. - tester_V - Jan-04-2023

Thank you!
That is what I need Smile
I kind of used to how quick and good you are guys, but I am still astonished by the skills you have...
And a little bit jealous... Wink

Thank you!