Created
June 6, 2016 00:42
-
-
Save vlad-bezden/668d0d657a03d22aebaf7a6570645173 to your computer and use it in GitHub Desktop.
Program calculates time such as 5:5 + 22:16 + 1:23:45 in hh:mm:ss format. It allows to enter time with '.' or with ':' as a time separator
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import sys | |
import datetime | |
from time import strptime | |
def process_input(user_input): | |
"""Parses user input and returns parsed time. """ | |
time_separator = '.' | |
time_tokens = 3 | |
user_input = user_input.replace(':', time_separator) # replace separator to common one | |
tokens = len(user_input.split(time_separator)) | |
if tokens > time_tokens: | |
raise ValueError('Invalid time format. It has to be in hh.mm.ss, mm.ss or ss format') | |
partitions = time_separator.join('%H.%M.%S'.split(time_separator)[-tokens:]) | |
return strptime(user_input, partitions) | |
def collect_data(): | |
"""Collects time. """ | |
total_time = datetime.datetime(1,1,1) | |
print('Enter time in format following format hh.mm.ss, mm.ss or ss. Press Enter key to exit') | |
while True: | |
try: | |
user_input = input() | |
if user_input == '': | |
print('\nTotal time:', total_time.time()) | |
break | |
else: | |
entered_time = process_input(user_input) | |
total_time += datetime.timedelta(hours=entered_time.tm_hour, minutes=entered_time.tm_min, seconds=entered_time.tm_sec) | |
print(total_time.time()) | |
except ValueError as e: | |
print (str(e)) | |
def main(): | |
"""Main function and starting point of the program. """ | |
try: | |
collect_data() | |
sys.exit(0) | |
except Exception as e: | |
print('Unhandled exception', str(e)) | |
sys.exit(1) | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment