Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/env python
- # -*- coding: utf-8 -*-
- # for http://www.reddit.com/r/dailyprogrammer/comments/pjsdx/difficult_challenge_2/
- import time, math, sys
- class Timer:
- running = False
- start = 0
- hour = 60*60
- minute = 60
- log = None
- def start_stop(self):
- if self.running:
- i = self.format_time(self.get_time_diff())
- self.running = False
- self.log.write('Finished: %s\n' % i)
- self.log.close()
- print('Clock stopped. Time is: %s' % i)
- return
- self.start = time.time()
- self.running = True
- self.log = open('timer.log', mode='w')
- print('Clock started.')
- def lap(self):
- if not self.running:
- print('You need to start the clock before you can get lap times.')
- return
- i = self.format_time(self.get_time_diff())
- self.log.write('Lap: %s\n' % i)
- print('Lap time is: %s' % i)
- def quit(self):
- if self.running:
- self.start_stop()
- sys.exit()
- def get_time_diff(self):
- return time.time() - self.start
- def format_time(self, seconds):
- h = '00'
- m = '00'
- s = '00'
- ms = '000'
- if (seconds >= self.hour):
- hours = int(math.floor(seconds/self.hour))
- h = '%02d' % hours
- seconds = seconds % self.hour
- if (seconds >= self.minute):
- minutes = int(math.floor(seconds/self.minute))
- m = '%02d' % minutes
- seconds = seconds % self.minute
- if (seconds > 0):
- secs = int(math.floor(seconds))
- s = '%02d' % secs
- seconds = seconds % 1
- if (seconds > 0):
- ms = '%s' % seconds
- ms = ms[2:5]
- return '%s:%s:%s.%s' % (h, m, s, ms)
- print('Welcome to timer!\nAvailable commands are (s)tart/(s)top, (l)ap time and (q)uit.')
- t = Timer();
- while True:
- try:
- command = input('Command: ').strip()
- except EOFError:
- print('')
- continue
- if not len(command):
- continue
- command = command[0]
- if 'l' == command:
- t.lap()
- elif 's' == command:
- t.start_stop()
- elif 'q' == command:
- t.quit()
- else:
- print('invalid command "%s", plese try again.' % command)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement