I would use Regex to find the times in the text,
import re
regex = re.compile(r'(d{1,2}:dd)')
times = regex.findall(line)
and use datetime and dateutil.relativedelta to find the parking time,
from datetime import datetime
from dateutil.relativedelta import relativedelta
parking_time = relativedelta(datetime.strptime(times[0] , '%H:%M'), datetime.strptime(times[1] , '%H:%M'))
minutes = abs((parking_time.hours * 60) + parking_time.minutes)
So, all together would be:
import re
from datetime import datetime
from dateutil.relativedelta import relativedelta
which_car = input("Please write your license number: ")
with open(file, 'r') as f:
for line in f:
if line.startswith(which_car):
size = line.split(' ')[1]
regex = re.compile(r'(d{1,2}:dd)')
times = regex.findall(line)
# Update - Ex. 3:27 -> 3:30, 3:35 -> 3:30
for i in range(len(times)):
minute = int(times[i].split(':')[1])
if minute - ((minute // 15) * 15) < 7.5:
minute = (minute // 15) * 15
else:
minute = (minute // 15 + 1) * 15
times[i] = times[i].split(':')[0] + ':' + str(minute)
parking_time = relativedelta(datetime.strptime(times[0] , '%H:%M'), datetime.strptime(times[1] , '%H:%M'))
minutes = abs((parking_time.hours * 60) + parking_time.minutes)
parking_cost = (minutes // 30) * 20
total_cost = parking_cost # Default size is small
if size == 'big':
total_cost = parking_cost * 1.5
elif size == 'medium':
total_cost = parking_cost * 1.25
I suggest using with when working with files since you don't have to worry about closing the file manually anymore.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…