A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from http://mail.python.org/pipermail/python-checkins/2002-March/024674.html below:

[Python-checkins] CVS: python/nondist/sandbox/datetime datetime.py,NONE,1.1 test_datetime.py,NONE,1.1

[Python-checkins] CVS: python/nondist/sandbox/datetime datetime.py,NONE,1.1 test_datetime.py,NONE,1.1Guido van Rossum gvanrossum@users.sourceforge.net
Fri, 01 Mar 2002 13:00:52 -0800
Update of /cvsroot/python/python/nondist/sandbox/datetime
In directory usw-pr-cvs1:/tmp/cvs-serv5784

Added Files:
	datetime.py test_datetime.py 
Log Message:
datetime prototype in Python

--- NEW FILE: datetime.py ---
import time as _time

class basetime(object):
    """Abstract date/time type.

    See http://effbot.org/ideas/time-type.htm
    """

    __slots__ = []

    def timetuple(self):
        raise NotImplementedError

    def utctimetuple(self):
        raise NotImplementedError

    def __cmp__(self, other):
        raise NotImplementedError

    def __hash__(self):
        raise NotImplementedError


# XXX deltaobject?

class datetime(basetime):
    """Concrete date/time type -- prototype implemented in Python.

    See http://www.zope.org/Members/fdrake/DateTimeWiki/FrontPage
    """

    __isdst = None

    def __init__(self, year, month, day, hour=0, minute=0, second=0,
                 microsecond=0, tzoffset=None):
        assert 1 <= year <= 9999
        assert 1 <= month <= 12
        assert 1 <= day <= 31 # XXX calendrical check
        assert 0 <= hour <= 23
        assert 0 <= minute <= 59
        assert 0 <= second <= 59
        assert 0 <= microsecond <= 999999
        if tzoffset is None:
            if datetime.__isdst is None:
                datetime.__isdst = _time.localtime()[-1]
            if datetime.__isdst > 0:
                tzoffset = -(_time.altzone/60)
            else:
                tzoffset = -(_time.timezone/60)
        assert -1439 <= tzoffset <= 1439
        self.__year = year
        self.__month = month
        self.__day = day
        self.__hour = hour
        self.__minute = minute
        self.__second = second
        self.__microsecond = microsecond
        self.__tzoffset = tzoffset # minutes east of UTC

    def new(cls, *args, **kwds):
        return cls(*args, **kwds)
    new = classmethod(new)

    def fromtimestamp(cls, t):
        y, m, d, hh, mm, ss, weekday, jday, dst = _time.localtime(t)
        us = int((t % 1.0) * 1000000)
        if dst > 0:
            tz = - _time.altzone/60
        else:
            tz = - _time.timezone/60
        return cls(y, m, d, hh, mm, ss, us, tz)
    fromtimestamp = classmethod(fromtimestamp)

    def now(cls):
        t = _time.time()
        return cls.fromtimestamp(t)
    now = classmethod(now)

    def utcfromtimestamp(cls, t):
        y, m, d, hh, mm, ss, weekday, jday, dst = _time.gmtime(t)
        us = int((t % 1.0) * 1000000)
        return cls(y, m, d, hh, mm, ss, us, 0)
    utcfromtimestamp = classmethod(utcfromtimestamp)

    def utcnow(cls):
        t = _time.time()
        return cls.utcfromtimestamp(t)
    utcnow = classmethod(utcnow)

    # Read-only field accessors
    year = property(lambda self: self.__year, doc="year (1-9999)")
    month = property(lambda self: self.__month, doc="month (1-12)")
    day = property(lambda self: self.__day, doc="day (1-31)")
    hour = property(lambda self: self.__hour, doc="hour (0-23)")
    minute = property(lambda self: self.__minute, doc="minute (0-59)")
    second = property(lambda self: self.__second, doc="second (0-59)")
    microsecond = property(lambda self: self.__microsecond,
                           doc="microsecond (0-999999)")
    tzoffset = property(lambda self: self.__tzoffset,
                        doc="time zone offset in minutes east of UTC")

    def _mktime(self):
        # Helper to call time.mktime()
        y, m, d = self.__year, self.__month, self.__day
        hh, mm, ss = self.__hour, self.__minute, self.__second
        mm -= self.__tzoffset # tzoffset is negative in the US
        ss -= _time.timezone # but time.timezone has the opposite sign!
        return _time.mktime((y, m, d, hh, mm, ss, -1, -1, -1))

    def _timestamp(self):
        # Helper like _mktime() that adds microseconds
        return self._mktime() + 0.000001 * self.__microsecond

    def timetuple(self):
        """Return local time tuple compatible with time.localtime()."""
        return _time.localtime(self._mktime())

    def utctimetuple(self):
        """Return UTC time tuple compatible with time.gmtime()."""
        return _time.gmtime(self._mktime())

    def __cmp__(self, other):
        """Three-way comparison."""
        if isinstance(other, datetime):
            if other.__tzoffset == self.__tzoffset:
                y, m, d = self.__year, self.__month, self.__day
                hh, mm, ss = self.__hour, self.__minute, self.__second
                tz = self.__tzoffset
                y2, m2, d2 = other.__year, other.__month, other.__day
                hh2, mm2, ss2 = other.__hour, other.__minute, other.__second
                tz2 = other.__tzoffset
                return cmp((y, m, d, hh, mm, ss, tz),
                           (y2, m2, d2, hh2, mm2, ss2, tz2))
            else:
                return cmp(self._timestamp(), other._timestamp())
        else:
            return NotImplemented

    def __hash__(self):
        """Hash."""
        y, m, d = self.__year, self.__month, self.__day
        hh, mm, ss = self.__hour, self.__minute, self.__second
        us, tz = self.__microsecond, self.__tzoffset
        return hash((y, m, d, hh, mm, ss, us, tz))

    def ctime(self):
        return _time.strftime("%c", _time.localtime(self._mktime()))

    def strftime(self, fmt):
        return _time.strftime(fmt, _time.localtime(self._mktime()))

    def utcctime(self):
        return _time.strftime("%c", _time.gmtime(self._mktime()))

    def utcstrftime(self, fmt):
        return _time.strftime(fmt, _time.gmtime(self._mktime()))

    # __add__, __sub__?

def _test():
    now = _time.time()
    print _time.ctime(now)
    t = datetime.fromtimestamp(now)
    print t.ctime(), divmod(t.tzoffset, 60), t.hour
    u = datetime.utcfromtimestamp(now)
    print u.utcctime(), divmod(u.tzoffset, 60), u.hour
    assert t == u

if __name__ == "__main__":
    _test()

--- NEW FILE: test_datetime.py ---
"""Test date/time type.

See http://www.zope.org/Members/fdrake/DateTimeWiki/TestCases
"""

import sys
import unittest

from datetime import datetime

class TestDateTime(unittest.TestCase):

    def test_basic_attributes(self):
        dt = datetime.new(2002, 3, 1, 12, 0, 0)
        self.assertEqual(dt.year, 2002)
        self.assertEqual(dt.month, 3)
        self.assertEqual(dt.day, 1)
        self.assertEqual(dt.hour, 12)
        self.assertEqual(dt.minute, 0)
        self.assertEqual(dt.second, 0)

    def test_tz_independent_comparing(self):
        dt1 = datetime.new(2002, 3, 1, 9, 0, 0, tzoffset=-60)
        dt2 = datetime.new(2002, 3, 1, 10, 0, 0, tzoffset=-60)
        dt3 = datetime.new(2002, 3, 1, 10, 0, 0, tzoffset=0)
        self.assertEqual(dt1, dt3)
        self.assert_(dt2 > dt3)

def test_suite():
    s1 = unittest.makeSuite(TestDateTime, 'test')
    return unittest.TestSuite([s1])

def test_main():
    r = unittest.TextTestRunner(stream=sys.stdout, verbosity=2)
    s = test_suite()
    r.run(s)

if __name__ == "__main__":
    test_main()




RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4