Link to project:
https://www.freecodecamp.org/learn/scientific-computing-with-python/build-a-time-calculator-project/build-a-time-calculator-project
Hi guys, I am having trouble with my code for the time calculator project in the scientific computing with python course. So far, I have been calculating the addition of time and the number of days. I have ignored the days (monday, tuesday, etc) for now. There is a bug. If my input in the function is time in am, it works correctly, but when it is in pm, it is buggy and I am not sure why. I have gone through step by step what my code would do with the following input: ‘11:20 PM’, ‘24:30’ but my calculations/output is different to what python is doing. I would like a helping hand in what’s wrong with my code thanks!
code:
def add_time(start, duration, day_of_the_week=''):
# Declaring variables
days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
current_day = day_of_the_week.lower().capitalize()
#print(current_day)
am = 'AM'
pm = 'PM'
day_or_afternoon = '' # Where am or pm goes into
adder = 0
no_of_days = 0
# Splitting duration into hours and minutes
duration = duration.split(':')
duration_hours = int(duration[0])
duration_minutes = int(duration[1])
#print(hours, minutes)
# Checking how many 24 hours in duration_hours
while duration_hours > 24:
duration_hours -= 24
no_of_days += 1
#print(adder)
#print(duration_hours)
# Checking AM or PM
start = start.split()
#print(start)
day_or_afternoon = start[1]
#print(day_or_afternoon)
# Splitting start into hours and minutes
start = start[0].split(':')
#print(start)
start_hours = int(start[0])
start_minutes = int(start[1])
#print(start_hours, start_minutes)
# Adding hours
start_hours += duration_hours
while start_hours > 12:
# am may switch to pm
if day_or_afternoon == am:
day_or_afternoon = pm
start_hours -= 12
# pm may switch to am and become a new day
if day_or_afternoon == pm:
day_or_afternoon = am
start_hours -= 12
no_of_days += 1
# Adding minutes
start_minutes += duration_minutes
while start_minutes > 59:
start_minutes -= 60
start_hours += 1
if start_hours > 12 and day_or_afternoon == am:
day_or_afternoon = pm
start_hours -= 12
elif start_hours > 12 and day_or_afternoon == pm:
day_or_afternoon = am
start_hours -= 12
no_of_days += 1
# Note that if none of the if statements are met, then it must mean the current value of time and hours is already valid.
if no_of_days != 0:
formatted_days = f'({no_of_days} days later)' if no_of_days >=2 else f'(next day)'
else:
formatted_days = f''
new_time = (f'{start_hours if start_hours != 0 else '00'}:{start_minutes if start_minutes != 0 else '00'} {day_or_afternoon} {formatted_days}').strip()
return new_time
if __name__ == '__main__':
print(add_time('11:20 PM', '24:30'))
# Returns: 6:10 PM