banner

© 2004-20 ict4u.net

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 = datetime.today().year
cMonth = datetime.today().month
cDay = datetime.today().day
cHour = datetime.today().hour
cMinute = datetime.today().minute

# 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
try:
	assert startDate <= currentDate
	diffDate = currentDate - startDate
except:
	AssertionError(print("End time is after start time"))
	timeOK = False

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