-3

How do I subtract two times to get a duration in Python?

I have tried the following code below using datetime.

Input for start time= 20-07-2020 11:00:00

Input for stop time= 20-07-2020 13:30:00

The output I would like is 2.5 hours or 2 hours 30 minutes

from datetime import datetime

print("Enter 11:00 13:30 for a task starting at 11am and ending at 1:30 pm.")
start=str(input("Enter the start time:"))
stop=str(input("Enter the stop time:"))

format_date= "%d-%m-%Y %H:%M:%S"
duration=datetime.strptime(start,format_date)-datetime.strptime(stop,format_date)
duration
Task1_start=datetime.strptime(start,format_date)
Task1_stop=datetime.strptime(stop,format_date)

print(f'Start:{Task1_start}, Stop:{Task1_stop}')
  • exactly how you would guess if you just took a stab in the dark `Task1_stop - Task1_start` (ps you should probably consider using `date_util.parser.parse` to convert string input to dates) – Joran Beasley Jul 30 '20 at 19:50
  • 1
    Check this post: https://stackoverflow.com/questions/25439279/python-calculating-time-difference-to-give-years-months-days-hours-minutes – Mike67 Jul 30 '20 at 19:57
  • date `20-07-2020` - `day-month-year` can't match to `%m-%d-%Y` which means `month-day-year`. You have wrong order of `day` and `month` – furas Jul 30 '20 at 21:25

1 Answers1

0

Date 20-07-2020 - day-month-year can't match to your %m-%d-%Y which means month-day-year. You have wrong order of day and month. So you have to use %d-%m instead of %m-%d

BTW: you have to caluculate stop - start instead of start - stop

from datetime import datetime

start = '20-07-2020 11:00:00'
stop = '20-07-2020 13:30:00'

format_date = "%d-%m-%Y %H:%M:%S"

dt_start = datetime.strptime(start, format_date)
dt_stop  = datetime.strptime(stop, format_date)

duration = dt_stop - dt_start

print(f'Start: {dt_start}, Stop: {dt_stop}')
print(duration)

Result

Start: 2020-07-20 11:00:00, Stop: 2020-07-20 13:30:00
2:30:00

To format it you need to get total seconds and calculate hours, minutes, seconds

rest = duration.total_seconds()
hours = int(rest // (60*60))
rest = rest % (60*60)
minutes = int(rest // 60)
seconds = int(rest % 60)

print(f"{hours} hours, {minutes} minutes, {seconds} seconds")

Result

2 hours, 30 minutes, 0 seconds

Or you have to convert duration to string and then split it

hours, minutes, seconds = str(duration).split(':')

print(f"{hours} hours, {minutes} minutes, {seconds} seconds")

Result

2 hours, 30 minutes, 00 seconds

BTW: when you convert duration to string then it runs code similar to my calculations with total_seconds - I checked this in source code.

furas
  • 134,197
  • 12
  • 106
  • 148