Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #24989

Re: simpler increment of time values?

References <CAHzaPEO5D498zepGC0EVVURdUE7qxYJk6ksd5yS_Xj_hh5iiyQ@mail.gmail.com> <CAHzaPEMKGbUPhpfaB5bFkxJkMsmHrCzPZojYB7ZVO2r8P0MGAg@mail.gmail.com>
Date 2012-07-06 23:48 +0200
Subject Re: simpler increment of time values?
From Vlastimil Brom <vlastimil.brom@gmail.com>
Newsgroups comp.lang.python
Message-ID <mailman.1874.1341611306.4697.python-list@python.org> (permalink)

Show all headers | View raw


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)))

# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #

Back to comp.lang.python | Previous | Next | Find similar | Unroll thread


Thread

Re: simpler increment of time values? Vlastimil Brom <vlastimil.brom@gmail.com> - 2012-07-06 23:48 +0200

csiph-web