cc1  v2.1
CC1 source code docs
 All Classes Namespaces Files Functions Variables Pages
formatters.py
Go to the documentation of this file.
1 # -*- coding: utf-8 -*-
2 # @COPYRIGHT_begin
3 #
4 # Copyright [2010-2014] Institute of Nuclear Physics PAN, Krakow, Poland
5 #
6 # Licensed under the Apache License, Version 2.0 (the "License");
7 # you may not use this file except in compliance with the License.
8 # You may obtain a copy of the License at
9 #
10 # http://www.apache.org/licenses/LICENSE-2.0
11 #
12 # Unless required by applicable law or agreed to in writing, software
13 # distributed under the License is distributed on an "AS IS" BASIS,
14 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 # See the License for the specific language governing permissions and
16 # limitations under the License.
17 #
18 # @COPYRIGHT_end
19 
20 ##
21 # @package src.wi.utils.formatters
22 #
23 # @author Piotr Wójcik
24 # @date 24.03.2011
25 #
26 
27 from django.utils.encoding import force_unicode
28 from django.utils.translation import ngettext, ugettext_lazy as _
29 
30 
31 ##
32 #
33 # Takes an amount of seconds and turns it into a human-readable amount of time.
34 #
35 def time_from_sec(seconds, separator=', '):
36 
37  suffixes = [(lambda count: ngettext(' day', ' days', count) % {'count': count}),
38  (lambda count: _(' h') % {'count': count}),
39  (lambda count: _(' min') % {'count': count}),
40  (lambda count: _(' s') % {'count': count})]
41 
42  # the formatted time string to be returned
43  time = []
44 
45  # the pieces of time to iterate over (days, hours, minutes, etc)
46  # - the first piece in each tuple is the suffix (d, h, w)
47  # - the second piece is the length in seconds (a day is 60s * 60m * 24h)
48  parts = [(suffixes[0], 60 * 60 * 24),
49  (suffixes[1], 60 * 60),
50  (suffixes[2], 60),
51  (suffixes[3], 1)]
52 
53  # for each time piece, grab the value and remaining seconds, and add it to
54  # the time string
55  for suffix, length in parts:
56  value = seconds / length
57  if value > 0:
58  seconds = seconds % length
59  time.append('%s%s' % (str(value), force_unicode(suffix(int(value))))) # (suffix, (suffix, suffix + 's')[value > 1])[add_s]))
60  if seconds < 1:
61  break
62 
63  return separator.join(time)
64