Created
February 22, 2013 13:34
-
-
Save tsileo/5013407 to your computer and use it in GitHub Desktop.
Convert relative interval string into seconds.
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 re | |
def _interval_string_to_seconds(interval_string): | |
"""Convert internal string like 1M, 1Y3M, 3W to seconds""" | |
interval_exc = "Bad interval format for {0}".format(interval_string) | |
interval_dict = {"s": 1, "m": 60, "h": 3600, "D": 86400, | |
"W": 7*86400, "M": 30*86400, "Y": 365*86400} | |
interval_regex = re.compile("^(?P<num>[0-9]+)(?P<ext>[smhDWMY])") | |
seconds = 0 | |
while interval_string: | |
match = interval_regex.match(interval_string) | |
if match: | |
num, ext = int(match.group("num")), match.group("ext") | |
if num > 0 and ext in interval_dict: | |
seconds += num * interval_dict[ext] | |
interval_string = interval_string[match.end():] | |
else: | |
raise Exception(interval_exc) | |
else: | |
raise Exception(interval_exc) | |
return seconds |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment