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

todo: expands it for all time config entries;
f2b-perfom-prepare-716
sebres 2014-05-14 16:01:35 +02:00
parent 5767191988
commit ee94daa121
1 changed files with 29 additions and 0 deletions

View File

@ -22,6 +22,7 @@ __copyright__ = "Copyright (c) 2004 Cyril Jaquier"
__license__ = "GPL"
import datetime
import re
import time
@ -96,3 +97,31 @@ class MyTime:
return time.localtime(x)
else:
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)