wcs/wcs/qommon/humantime.py

92 lines
2.8 KiB
Python

# w.c.s. - web application for online forms
# Copyright (C) 2005-2010 Entr'ouvert
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, see <http://www.gnu.org/licenses/>.
import re
from . import _
_minute = 60
_hour = 60 * 60
_day = _hour * 24
_month = _day * 31
_year = int(_day * 365.25)
def list2human(stringlist):
'''Transform a string list to human enumeration'''
beginning = stringlist[:-1]
if not beginning:
return "".join(stringlist)
return _("%(first)s and %(second)s") % {'first': _(", ").join(beginning), 'second': stringlist[-1]}
_humandurations = (( (N_("day"), N_("days")), _day),
( (N_("hour"), N_("hours")), _hour),
( (N_("month"), N_("months")), _month),
( (N_("year"), N_("years")), _year),
( (N_("minute"), N_("minutes")), _minute),
( (N_("second"), N_("seconds")), 1),)
def timewords():
'''List of words one can use to specify durations'''
result = []
for words, quantity in _humandurations:
for word in words:
result.append(_(word))
return result
def humanduration2seconds(humanduration):
if not humanduration:
raise ValueError()
seconds = 0
for words, quantity in _humandurations:
for word in words:
word = _(word)
m = re.search(r"(\d+)\s*\b%s\b" % word, humanduration)
if m:
seconds = seconds + int(m.group(1)) * quantity
break
return seconds
def seconds2humanduration(seconds):
'''Convert a time range in seconds to a human string representation
'''
# years = int(seconds / _year)
# secons = seconds - _year * years
# months = int(seconds / _month)
# seconds = seconds - _month * months
if not type(seconds) is int:
return ""
days = int(seconds / _day)
seconds = seconds - _day * days
hours = int(seconds / _hour)
seconds = seconds - _hour * hours
minutes = int(seconds / _minute)
seconds = seconds - _minute * minutes
human = []
if days:
human.append(_("%s days") % days)
if hours:
human.append(_("%s hours") % hours)
if minutes:
human.append(_("%s minutes") % minutes)
if seconds:
human.append(_("%s seconds") % seconds)
return list2human(human)