Adding Time in Python


Suppose we have a string that is representing a 12-hour clock time with suffix am or pm, and an integer n is also given, we will add n minutes to the time and return the new time in the same format.

So, if the input is like s = "8:20pm" and n = 150, then the output will be 10:50pm

To solve this, we will follow these steps −

  • h, m := take the hour and minute part from s

  • h := h mod 12

  • if the time s is in 'pm', then

    • h := h + 12

  • t := h * 60 + m + n

  • h := quotient of t/60, m := remainder of t/60

  • h := h mod 24

  • suffix := 'am' if h < 12 otherwise 'pm'

  • h := h mod 12

  • if h is same as 0, then

    • h := 12

  • return the time h:m suffix

Let us see the following implementation to get better understanding −

Example

 Live Demo

class Solution:
   def solve(self, s, n):
      h, m = map(int, s[:-2].split(':'))
      h %= 12
      if s[-2:] == 'pm':
         h += 12
      t = h * 60 + m + n
      h, m = divmod(t, 60)
      h %= 24
      suffix = 'a' if h < 12 else 'p'
      h %= 12
      if h == 0:
         h = 12
      return "{:02d}:{:02d}{}m".format(h, m, suffix)
ob = Solution()
print(ob.solve("8:20pm", 150))

Input

"8:20pm", 150

Output

10:50pm

Updated on: 02-Sep-2020

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements