Python Forum
Need to sum up HHMMS AM/PM DD/MM/YYYY and a HH:MM:SS.
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Need to sum up HHMMS AM/PM DD/MM/YYYY and a HH:MM:SS.
#1
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.
Reply
#2
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
Reply
#3
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.
tester_V likes this post
Reply
#4
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!
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  regex to extract only yy or yyyy metalray 2 3,569 Jul-11-2018, 07:57 PM
Last Post: volcano63

Forum Jump:

User Panel Messages

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