remove unnecessary imports
[mygpo.git] / mygpo / utils.py
blob9664ae13decd45c111aa24df87b7496c2c39dc79
2 # This file is part of my.gpodder.org.
4 # my.gpodder.org is free software: you can redistribute it and/or modify it
5 # under the terms of the GNU Affero General Public License as published by
6 # the Free Software Foundation, either version 3 of the License, or (at your
7 # option) any later version.
9 # my.gpodder.org is distributed in the hope that it will be useful, but
10 # WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
11 # or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public
12 # License for more details.
14 # You should have received a copy of the GNU Affero General Public License
15 # along with my.gpodder.org. If not, see <http://www.gnu.org/licenses/>.
18 from datetime import datetime, timedelta
19 import time
21 def daterange(from_date, to_date=datetime.now(), leap=timedelta(days=1)):
22 while from_date <= to_date:
23 yield from_date
24 from_date = from_date + leap
25 return
27 def format_time(value):
28 """Format an offset (in seconds) to a string
30 The offset should be an integer or float value.
32 >>> format_time(0)
33 '00:00'
34 >>> format_time(20)
35 '00:20'
36 >>> format_time(3600)
37 '01:00:00'
38 >>> format_time(10921)
39 '03:02:01'
40 """
41 dt = datetime.utcfromtimestamp(value)
43 if dt.hour == 0:
44 return dt.strftime('%M:%S')
45 else:
46 return dt.strftime('%H:%M:%S')
48 def parse_time(value):
49 if value is None:
50 raise ValueError('None value in parse_time')
52 if isinstance(value, int):
53 # Don't need to parse already-converted time value
54 return value
56 if value == '':
57 raise ValueError('Empty valueing in parse_time')
59 for format in ('%H:%M:%S', '%M:%S'):
60 try:
61 t = time.strptime(value, format)
62 return t.tm_hour * 60*60 + t.tm_min * 60 + t.tm_sec
63 except ValueError, e:
64 continue
66 return int(value)
68 def parse_bool(val):
69 if isinstance(val, bool):
70 return val
71 if val.lower() == 'true':
72 return True
73 return False