- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
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
- Related Articles
- Adding value to sublists in Python
- Adding two values at a time from an array - JavaScript
- Adding two Python lists elements
- Adding a new column with the current time as a default value in MySQL?
- Adding Tuple to List and vice versa in Python
- Time Functions in Python?
- Adding a new column to existing DataFrame in Pandas in Python
- How to compare time in different time zones in Python?
- Getting current time in Python
- Getting formatted time in Python
- The time Module in Python
- 24-hour time in Python
- Adding K to each element in a Python list of integers
- Adding a Chartsheet in an excel sheet using Python XlsxWriter module
- Adding a new column to an existing DataFrame in Python Pandas

Advertisements