[kupfer: 4/11] utils: Add parse_time_interval
- From: Ulrik Sverdrup <usverdrup src gnome org>
- To: svn-commits-list gnome org
- Cc:
- Subject: [kupfer: 4/11] utils: Add parse_time_interval
- Date: Mon, 14 Dec 2009 20:10:41 +0000 (UTC)
commit 68fb4feb36f65e151bce31cc03c7ce08c377aba8
Author: Ulrik Sverdrup <ulrik sverdrup gmail com>
Date: Mon Dec 14 00:18:13 2009 +0100
utils: Add parse_time_interval
Add a simple function to parse time intervals given as strings, will
understand "1h 2 min" etc and return the number of seconds.
kupfer/utils.py | 40 ++++++++++++++++++++++++++++++++++++++++
1 files changed, 40 insertions(+), 0 deletions(-)
---
diff --git a/kupfer/utils.py b/kupfer/utils.py
index 7af7bdf..10bf784 100644
--- a/kupfer/utils.py
+++ b/kupfer/utils.py
@@ -183,3 +183,43 @@ def get_display_path_for_bytestring(filepath):
if desc.startswith(homedir) and homedir != desc:
desc = desc.replace(homedir, "~/", 1)
return desc
+
+def parse_time_interval(tstr):
+ """
+ Parse a time interval in @tstr, return whole number of seconds
+
+ >>> parse_time_interval("2")
+ 2
+ >>> parse_time_interval("1h 2m 5s")
+ 3725
+ >>> parse_time_interval("2 min")
+ 120
+ """
+ weights = {
+ "s": 1, "sec": 1,
+ "m": 60, "min": 60,
+ "h": 3600, "hours": 3600,
+ }
+ try:
+ return int(tstr)
+ except ValueError:
+ pass
+
+ total = 0
+ amount = 0
+ # Split the string in runs of digits and runs of characters
+ for isdigit, group in itertools.groupby(tstr, lambda k: k.isdigit()):
+ part = "".join(group).strip()
+ if not part:
+ continue
+ if isdigit:
+ amount = int(part)
+ else:
+ total += amount * weights.get(part.lower(), 0)
+ amount = 0
+ return total
+
+
+if __name__ == '__main__':
+ import doctest
+ doctest.testmod()
[
Date Prev][
Date Next] [
Thread Prev][
Thread Next]
[
Thread Index]
[
Date Index]
[
Author Index]