introduced string to seconds (str2seconds) for configuration entries with time;

todo: expands it for all time config entries;
pull/1346/head
sebres 11 years ago
parent 26dd6d7425
commit a3e0cc9830

@ -22,6 +22,7 @@ __copyright__ = "Copyright (c) 2004 Cyril Jaquier"
__license__ = "GPL" __license__ = "GPL"
import datetime import datetime
import re
import time import time
@ -96,3 +97,32 @@ class MyTime:
return time.localtime(x) return time.localtime(x)
else: else:
return time.localtime(MyTime.myTime) return time.localtime(MyTime.myTime)
##
# Wraps string expression like "1h 2m 3s" into number contains seconds (3723).
# The string expression will be evaluated as mathematical expression, spaces between each groups
# will be wrapped to "+" operand (only if any operand does not specified between).
# Because of case insensitivity and overwriting with minutes ("m" or "mm"), the short replacement for month
# are "mo" or "mon" (like %b by date formating).
# Ex: 1hour+30min = 5400
# 0d 1h 30m = 5400
# 1year-6mo = 15778800
# 6 months = 15778800
# warn: month is not 30 days, it is a year in seconds / 12, the leap years will be respected also:
# >>>> float(Test.str2seconds("1month")) / 60 / 60 / 24
# 30.4375
# >>>> float(Test.str2seconds("1year")) / 60 / 60 / 24
# 365.25
#
# @returns number (calculated seconds from expression "val")
#@staticmethod
def str2seconds(val):
for rexp, rpl in (
(r"days?|da|dd?", 24*60*60), (r"week?|wee?|ww?", 7*24*60*60), (r"months?|mon?", (365*3+366)*24*60*60/4/12), (r"years?|yea?|yy?", (365*3+366)*24*60*60/4),
(r"seconds?|sec?|ss?", 1), (r"minutes?|min?|mm?", 60), (r"hours?|ho|hh?", 60*60),
):
val = re.sub(r"(?i)(?<=[\d\s])(%s)\b" % rexp, "*"+str(rpl), val)
val = re.sub(r"(\d)\s+(\d)", r"\1+\2", val);
return eval(val)
str2seconds = staticmethod(str2seconds)

Loading…
Cancel
Save