How can I make my Time Calculator code more Efficient?

Hello! I’m just beginning to learn code and would like some help with how I can make my code more legible in a professional environment for my peers (i.e. declaring variable names). Also is there any way to make my code more efficient? I looked/fixed for any repeating code and tried to make it as concise as possible from my knowledge. Any input would be of great value!

My Code passed all tests. This is merely for improvement. Please request if my output is necessary.

def add_time(start, duration, day=False):
    hr_str1, scnd_hlf = start.split(':')
    mn_str1, meridiem = scnd_hlf.split()
    hr_str2, mn_str2 = duration.split(':')
    if day:
      day_week = day
    else:
      day_week = ''
    
    hr_int1, mn_int1, hr_int2, mn_int2 = int(hr_str1), int(mn_str1), int(hr_str2), int(mn_str2)

    if meridiem == 'PM': hr_int1 + 12
    ttl_hr = hr_int1 + hr_int2
    ttl_mn = mn_int1 + mn_int2
    
    days = 0
    halfdays = 0
    new_hr = new_mn = ''
    new_day = ''
    daylist = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
    if ttl_mn >= 60:
      ttl_hr += (ttl_mn // 60)
      ttl_mn = ttl_mn % 60
    if ttl_hr >= 24:
      days += (ttl_hr // 24)
      if ttl_hr == 24:
        ttl_hr = 12
      else:
        ttl_hr = ttl_hr % 24
    if ttl_hr >= 12:
      if meridiem == 'AM':
        meridiem = 'PM'
        if ttl_hr != 12:
          ttl_hr = ttl_hr - 12
      elif meridiem == 'PM':
        meridiem = 'AM'
        days += 1
        if ttl_hr != 12:
          ttl_hr = ttl_hr - 12

    new_hr = str(ttl_hr)
    if ttl_mn <= 9: 
      new_mn = str(ttl_mn).rjust(2,'0') 
    else: 
      new_mn = str(ttl_mn)
    
    for i in daylist:
      if day_week.lower() == i.lower():
        new_day = daylist[(daylist.index(day_week.title()) + days) % 7]
    
    if days == 1:
      new_time = "{}:{} {}{}{}{}".format(new_hr, new_mn,meridiem, ',' if new_day != '' else '', new_day.rjust(len(new_day)+1) if new_day != '' else '', (' (' + 'next' + ' day' + ')'))
    else:
      new_time = "{}:{} {}{}{}{}".format(new_hr, new_mn,meridiem, ',' if new_day != '' else '', new_day.rjust(len(new_day)+1) if new_day != '' else '', (' (' + str(days) + ' days later' + ')') if days >= 1 else '')

    return new_time

Some suggestions:

  • using False as the default value for day implies that it’s a boolean (it’s not). Using None would be better.
  • Code is read much more than it is written so try not to go too crazy on abbreviations (it took me a bit to understand that “scnd” was “second”, “ttl” was “total” and “mn” was “minutes”).
hr_int1, mn_int1, hr_int2, mn_int2 = int(hr_str1), int(mn_str1), int(hr_str2), int(mn_str2)

Don’t do this, split it into four separate lines.

ttl_hr = ttl_hr % 24

You can use %= here, which behaves just like +=.

new_mn = str(ttl_mn).rjust(2,'0') 

zfill() would be better for padding with zeros here.

if days == 1:
      new_time = "{}:{} {}{}{}{}".format(new_hr, new_mn,meridiem, ',' if new_day != '' else '', new_day.rjust(len(new_day)+1) if new_day != '' else '', (' (' + 'next' + ' day' + ')'))
    else:
      new_time = "{}:{} {}{}{}{}".format(new_hr, new_mn,meridiem, ',' if new_day != '' else '', new_day.rjust(len(new_day)+1) if new_day != '' else '', (' (' + str(days) + ' days later' + ')') if days >= 1 else '')

return new_time

You’re doing way too much per line here which makes things difficult to follow, and the lines themselves are way too long. PEP8 recommends a maximum line length of 79 characters.

Overall, looking good. Keep it up!

For reference, here’s my solution:

def add_time(start, duration, start_day=None):
    start_time, start_meridiem = start.split()
    start_time = [int(t) for t in start_time.split(":")]
    if start_meridiem == "PM":
        start_time[0] += 12

    duration = [int(t) for t in duration.split(":")]

    days_elapsed, duration[0] = divmod(duration[0], 24)
    end_time = [st + dur for st, dur in zip(start_time, duration)]

    if end_time[1] >= 60:
        end_time[0] += 1
        end_time[1] %= 60

    if end_time[0] >= 24:
        days_elapsed += 1
        end_time[0] %= 24

    if end_time[0] == 0:
        end_time[0] = 12
        end_meridiem = "AM"
    elif 0 < end_time[0] < 12:
        end_meridiem = "AM"
    elif end_time[0] == 12:
        end_meridiem = "PM"
    elif end_time[0] > 12:
        end_time[0] -= 12
        end_meridiem = "PM"

    if start_day:
        day_names = [
            "monday", "tuesday", "wednesday",
            "thursday", "friday", "saturday", "sunday"
        ]
        start_index = day_names.index(start_day.lower())
        end_index = (start_index + days_elapsed) % 7
        end_day = day_names[end_index].title()
    else:
        end_day = None

    formatted_end_time = "{}:{:02} {}".format(*end_time, end_meridiem)
    formatted_end_day = f", {end_day}" if end_day else ""
    if days_elapsed == 0:
        formatted_days_elapsed = ""
    elif days_elapsed == 1:
        formatted_days_elapsed = " (next day)"
    else:
        formatted_days_elapsed = f" ({days_elapsed} days later)"

    new_time = "{}{}{}".format(
        formatted_end_time, formatted_end_day, formatted_days_elapsed
    )

    return new_time
1 Like

Thank you so much for your constructive criticism! I’ll take note of all this information. Is PEP8 standard for all python coding or are there different style guides for different problems?

Also I like what you did with the library. I found myself constantly manipulating the data in the library when I could have just did it once at the end to display according to the correct syntax.

I highly recommend you read the whole thing, but to quote PEP8 on PEP8:

A style guide is about consistency. Consistency with this style guide is important. Consistency within a project is more important. Consistency within one module or function is the most important.

An example of a project style guide would be the Google Python Style Guide.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.