Skip to content

Instantly share code, notes, and snippets.

@EddyLuten
Created December 13, 2013 22:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save EddyLuten/7952375 to your computer and use it in GitHub Desktop.
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.
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