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


Groups > comp.lang.python > #24989 > unrolled thread

Re: simpler increment of time values?

Started byVlastimil Brom <vlastimil.brom@gmail.com>
First post2012-07-06 23:48 +0200
Last post2012-07-06 23:48 +0200
Articles 1 — 1 participant

Back to article view | Back to comp.lang.python

This discussion starts older than the indexed window; earlier articles aren't shown. The article labeled Started by below is the oldest one visible, not the original post.


Contents

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

#24989 — Re: simpler increment of time values?

FromVlastimil Brom <vlastimil.brom@gmail.com>
Date2012-07-06 23:48 +0200
SubjectRe: simpler increment of time values?
Message-ID<mailman.1874.1341611306.4697.python-list@python.org>
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)))

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

[toc] | [standalone]


Back to top | Article view | comp.lang.python


csiph-web