DzITC
DzITC

Reputation: 879

Python : timedelta other way comparing time while each adding an hour

I'm building car parking system and I'm having some issues with comparing time. Let's say "John" should pay 5$ for one hour to park his car. John leaves his car for 3:30 hours in parking lot and makes a payment when the time for the parking stops at 3:33. So what I would like to get here is something like this, but the thing is that its non logical to make an if at each hour. What's the way to somehow just count the sum of the payment to calculate. Also what I didn't mention is that 3:33 is more then half hour so we can count another hour. But what I want to do here is that:

My code:

if Parking_Sum > datetime.timedelta(minutes=30):
            print ("You were parking for more then 30MINS You have to pay 5$")
            Price = 5
       elif Parking_Sum > datetime.timedelta(hours=1):
            print ("You were parking for more then hour You have to pay 10$")
            Price = 10
       elif Parking_Sum > datetime.timedelta(days=1):
            print ("You were parking for more then DAY You have to pay 120$")
            Price = 120

Upvotes: 0

Views: 384

Answers (2)

FObersteiner
FObersteiner

Reputation: 25594

you could use

import datetime
import math

def parkingcosts(price, t):
    return math.ceil(t.total_seconds()/3600)*price

price_per_h = 5

parkingtime = datetime.timedelta(minutes=30)
print(parkingcosts(price_per_h, parkingtime))
# 5
parkingtime = datetime.timedelta(hours=1.5)
print(parkingcosts(price_per_h, parkingtime))
# 10
parkingtime = datetime.timedelta(days=1)
print(parkingcosts(price_per_h, parkingtime))
# 120

I think the easiest way to get the hours from a timedelta object is to use .total_seconds(). Otherwise, there's .days, .seconds and .microseconds that you would have to sum up (no hours, minutes though... check dir(datetime.timedelta())).

Upvotes: 1

Ajay Srivastava
Ajay Srivastava

Reputation: 1181

Find the difference between entered time and exit time. Calculate total minutes, vehicle was in parking and then calculate the charges. Here is example -

time_entered = datetime(year=2019, month=9, day=2, hour=10, minute=9)
time_left = datetime(year=2019, month=9, day=2, hour=12, minute=40)
total_minutes = ((time_left - time_entered).total_seconds())//60
total_hours = (total_minutes//60 + 1) if total_minutes%60 > 30 else (total_minutes//60)
total_charges = total_hours*5

Upvotes: 1

Related Questions