Log In

Come Join Us!

Are you a
Computer / IT professional?
Join Tek-Tips Forums!
  • Talk With Other Members
  • Be Notified Of Responses
    To Your Posts
  • Keyword Search
  • One-Click Access To Your
    Favorite Forums
  • Automated Signatures
    On Your Posts
  • Best Of All, It's Free!

*Tek-Tips's functionality depends on members receiving e-mail. By joining you are opting in to receive e-mail.

Posting Guidelines

Promoting, selling, recruiting, coursework and thesis posting is forbidden.

Students Click Here

Need to add HH:MM:SS:MS

Need to add HH:MM:SS:MS

Need to add HH:MM:SS:MS

Does anybody knows how to add times in Python?
Need to add HH:MM:SS:MS
The file goes like this:
5/1/2020 2:40:31 PM, 5/1/2020 2:43:11 PM, 00:02:40.5449136,
5/1/2020 2:45:26 PM, 5/1/2020 2:48:17 PM, 00:02:50.8250927,
the third column is a timduration, need to sum it up.

Thank you.

RE: Need to add HH:MM:SS:MS


Quote (Tester_V)

Does anybody knows how to add times in Python?
Fortunately Python has a dedicated timedelta class for that purpose ( just like Java has Period and PHP has DateInterval ). That makes calculations simple ( and with Python's overloaded operators also intuitive ).
Unfortunately timedelta has no dedicated method to initialize it from a string, like datetime's .strptime(), so you have to spoonfeed it with integers :

CODE --> Python

from datetime import datetime, timedelta
import re

with open('Tester_V.txt') as file:
    for line in file:
        part = line.split(', ')

        first = datetime.strptime(part[0], '%m/%d/%Y %I:%M:%S %p')
        second = datetime.strptime(part[1], '%m/%d/%Y %I:%M:%S %p')

        deltapart = [int(one) for one in re.findall(r'\d+', part[2])]

        delta = timedelta(hours = deltapart[0], minutes = deltapart[1], seconds = deltapart[2], microseconds = deltapart[3])

        print('%s + %s = %s' % (first, delta, first + delta))
        print('%s + %s = %s' % (second, delta, second + delta)) 


RE: Need to add HH:MM:SS:MS

Thank you!

Red Flag This Post

Please let us know here why this post is inappropriate. Reasons such as off-topic, duplicates, flames, illegal, vulgar, or students posting their homework.

Red Flag Submitted

Thank you for helping keep Tek-Tips Forums free from inappropriate posts.
The Tek-Tips staff will check this out and take appropriate action.

Reply To This Thread

Posting in the Tek-Tips forums is a member-only feature.

Click Here to join Tek-Tips and talk with other members! Already a Member? Login

Close Box

Join Tek-Tips® Today!

Join your peers on the Internet's largest technical computer professional community.
It's easy to join and it's free.

Here's Why Members Love Tek-Tips Forums:

Register now while it's still free!

Already a member? Close this window and log in.

Join Us             Close