simpler increment of time values?
Vlastimil Brom
vlastimil.brom at gmail.com
Fri Jul 6 17:48:22 EDT 2012
Thanks to all for further comments!
Just for completeness and in case somebody would like to provide some
suggestions or corrections;
the following trivial class should be able to deal with the initial
requirement of adding or subtracting dateless time values
(hour:minute).
regards,
vbr
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
import re
class TrivialTime(object):
"""
Trivial, dateless, DST-less, TZN-less time in 24-hours cycle
only supporting hours and minutes; allows addition and subtraction.
"""
def __init__(self, hours=0, minutes=0):
self.total_minutes = (int(hours) * 60 + int(minutes)) % (60 * 24)
self.hours, self.minutes = divmod(self.total_minutes, 60)
def __add__(self, other):
return TrivialTime(minutes=self.total_minutes + other.total_minutes)
def __sub__(self, other):
return TrivialTime(minutes=self.total_minutes - other.total_minutes)
def __repr__(self):
return "TrivialTime({}, {})".format(self.hours, self.minutes)
def __str__(self):
return "{}.{:0>2}".format(self.hours, self.minutes)
@staticmethod
def fromstring(time_string, format_re=r"^([0-2]?\d?)[.:,-]\s*([0-5]\d)$"):
"""
Returns a TrivialTime instance according to the data from the
given string
with respect to the regex time format (two parethesised groups
for minutes and seconds respectively).
"""
time_string_match = re.match(format_re, time_string)
if not time_string_match:
raise ValueError("Time data cannot be obtained from the
given string and the format regex.")
return TrivialTime(hours=int(time_string_match.group(1)),
minutes=int(time_string_match.group(2)))
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
More information about the Python-list
mailing list