Created
December 13, 2013 22:18
-
-
Save EddyLuten/7952375 to your computer and use it in GitHub Desktop.
Little helper used to parse a natural time string such as "7 seconds" and convert the textual representation into seconds. This could be reduced into a single function, but this is how it was originally used.
This file contains 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 re | |
class NaturalTimeSpan: | |
time = 0 | |
def __init__(self, time_string): | |
BAD_STRING = 'Unsupported format string provided: %s' | |
matches = re.search('^(?P<quantity>\d+)\s+(?P<format>second|minute|hour|day|week|year)s?$', time_string) | |
if not matches: | |
raise Exception(BAD_STRING, time_string) | |
multiplier = { | |
'second': 1, | |
'minute': 60, | |
'hour' : 60 * 60, | |
'day' : 60 * 60 * 24, | |
'week' : 60 * 60 * 24 * 7, | |
'year' : 60 * 60 * 24 * 7 * 365 | |
}.get( matches.group('format'), None ) | |
if not multiplier: | |
raise Exception(BAD_STRING, time_string) | |
self.time = multiplier * int( matches.group('quantity') ) | |
def get_time(self): | |
""" Returns the time span in seconds """ | |
return self.time |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment