'Calculate the time [duplicate]

I had 2 things to do here,

  1. Print start time and end time.
  2. Calculate time.
import datetime
import re

logs = "432894u2398 start 7:00:00.100" , "432894u2398 end 7:03:24.400"

start_regex = r'start\s(\d+:\d+:\d+.\d+)'

end_regex = r'end\s(\d+:\d+:\d+.\d+)'


for line in logs:
    sr = re.search(start_regex, line)
    er = re.search(end_regex, line)
    if sr:
        print(f'transaction start time is: {sr.group(1)}')
    if er:
        print(f'transaction end time is: {er.group(1)}')

How do I calculate the time difference between them?



Solution 1:[1]

import datetime
import re

start, end = "432894u2398 start 7:00:00.100" , "432894u2398 end 7:03:24.400"

get_time_string = lambda s: re.split(r"(start|end) ", s)[2]
to_date = lambda s: datetime.datetime.strptime(get_time_string(s), '%H:%M:%S.%f')

delta = to_date(end) - to_date(start)
print(delta)
## 0:03:24.3000000

Solution 2:[2]

If you know that the log messages are always the same format, you could make your life easier by doing this:

from datetime import datetime

# Get the times out of the log message and parse them
start, end = list(map(lambda x: datetime.strptime(x.rsplit(" ")[1], "%H:%M:%S.%f"), logs))
# Calculate duration by subtracting datetimes
duration = end - start

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Gwang-Jin Kim
Solution 2 whege