© 2004-20

Elapsed Time

The code below demonstrates how to accept a time from the user, convert it to a date-time object then work out how long in hours and minutes the input was from the current time. Note: The input time is validated to ensure it is before the current time

# Author: Alan Knifton
# Date: 7 Nov 2109
# Purpose:Calculate the difference between two times

# import datetime
from datetime import datetime
import time

# setup a format string to validate the input against:
strFormat = '%H:%M' #numeric in the format dd/mm/yyyy

# use the today method to return various parts of the date
cYear =
cMonth =
cDay =
cHour =
cMinute =

# create the current date object with year, month, day, hour, minute, and second
currentDate = datetime(cYear, cMonth, cDay, cHour, cMinute, 00)

# assuming the same day allow the user to input the start time
strTime = input("Enter a the start time (hh:mm)")

objTimeStart = datetime.strptime(strTime,strFormat)   #convert using the specified date format

# Convert the input date to a full date/time object  so that arithmetic can be done
startDate = datetime(cYear, cMonth, cDay, objTimeStart.hour, objTimeStart.minute, 00)

# Difference between two dates
timeOK = True
	assert startDate <= currentDate
	diffDate = currentDate - startDate
	AssertionError(print("End time is after start time"))
	timeOK = False

if timeOK:
	print(f"Difference: {diffDate}\nMinutes:{diffDate.seconds//60}")