Hello!
I finished the second certified project and I feel quite good because it took me less effort than the first one. However, I think my code could be improved, I feel like I am using ‘if’ loops all the time! It does work, but I was wondering if someone has suggestions to make it more efficient/readible and to try to find a different way of thinking about these problems. Thank you all in advance!
My code:
def add_time(start, duration, day = None):
# separate in variables start hours, minutes and AM/PM
s_time = start.split(' ')[0]
s_hours = int(s_time.split(':')[0])
s_min = int(s_time.split(':')[1])
s_period = start.split(' ')[1]
# transform into a 24:00 format
if s_period == 'PM':
s_hours += 12
d_hours = int(duration.split(':')[0])
d_min = int(duration.split(':')[1])
# calculate total minutes
extra_hours = 0
if s_min + d_min > 60:
extra_hours = (s_min + d_min) // 60
final_min = (s_min + d_min) % 60
else:
final_min = s_min + d_min
# final_min does need to have two digits
if final_min < 10:
final_min = '0' + str(final_min)
# calculate total hours and extra days
extra_days = 0
if s_hours + d_hours + extra_hours > 24:
extra_days = (s_hours + d_hours + extra_hours) // 24
final_hours = (s_hours + d_hours + extra_hours) % 24
else:
final_hours = (s_hours + d_hours + extra_hours)
# encode AM/PM for the new time
if final_hours >= 12:
final_period = 'PM'
final_hours -= 12
if final_hours == 0:
final_hours = 12
else:
final_period = 'AM'
if final_hours == 0:
final_hours = 12
# print week day
if day:
day = day.lower().capitalize()
week =[
'Monday',
'Tuesday',
'Wednesday',
'Thursday',
'Friday',
'Saturday',
'Sunday'
]
if extra_days:
if extra_days == 1:
for i in range(len(week)):
if week[i] == day:
new_day = i + 1
if new_day > 7:
new_day = new_day % 7
new_time = f"{final_hours}:{final_min} {final_period}, {week[new_day]} (next day)"
elif extra_days > 1:
for i in range(len(week)):
if week[i] == day:
new_day = i + extra_days
if new_day > 7:
new_day = new_day % 7
new_time = f"{final_hours}:{final_min} {final_period}, {week[new_day]} ({extra_days} days later)"
else:
new_time = f"{final_hours}:{final_min} {final_period}, {day}"
else:
# print relative day
if extra_days:
if extra_days == 1:
new_time = f"{final_hours}:{final_min} {final_period} (next day)"
elif extra_days > 1:
new_time = f"{final_hours}:{final_min} {final_period} ({extra_days} days later)"
else:
new_time = f"{final_hours}:{final_min} {final_period}"
return new_time