diff options
-rw-r--r-- | date.py | 15 | ||||
-rw-r--r-- | test/unittest_date.py | 11 |
2 files changed, 23 insertions, 3 deletions
@@ -235,6 +235,19 @@ def todatetime(somedate): def datetime2ticks(somedate): return timegm(somedate.timetuple()) * 1000 +def ticks2datetime(ticks): + miliseconds, microseconds = divmod(ticks, 1000) + try: + return datetime.fromtimestamp(miliseconds) + except (ValueError, OverflowError): + epoch = datetime.fromtimestamp(0) + nb_days, seconds = divmod(int(miliseconds), 86400) + delta = timedelta(nb_days, seconds=seconds, microseconds=microseconds) + try: + return epoch + delta + except (ValueError, OverflowError): + raise + def days_in_month(somedate): return monthrange(somedate.year, somedate.month)[1] @@ -273,7 +286,7 @@ def ustrftime(somedate, fmt='%Y-%m-%d'): try: return unicode(somedate.strftime(str(fmt)), encoding) except ValueError, exc: - if '1900' not in exc.args[0]: + if somedate.year >= 1900: raise # datetime is not happy with dates before 1900 # we try to work around this, assuming a simple diff --git a/test/unittest_date.py b/test/unittest_date.py index 701a473..e05df34 100644 --- a/test/unittest_date.py +++ b/test/unittest_date.py @@ -18,11 +18,11 @@ """ Unittests for date helpers """ -from logilab.common.testlib import TestCase, unittest_main +from logilab.common.testlib import TestCase, unittest_main, tag from logilab.common.date import date_range, endOfMonth from logilab.common.date import add_days_worked, nb_open_days, \ - get_national_holidays, ustrftime + get_national_holidays, ustrftime, ticks2datetime from datetime import date, datetime, timedelta @@ -127,10 +127,17 @@ class DateTC(TestCase): def test_open_days_afternoon(self): self.assertOpenDays(self.datetimecls(2008, 5, 6, 14), self.datetimecls(2008, 5, 7, 14), 1) + @tag('posix', '1900') def test_ustrftime_before_1900(self): date = self.datetimecls(1328, 3, 12, 6, 30) self.assertEqual(ustrftime(date, '%Y-%m-%d %H:%M:%S'), u'1328-03-12 06:30:00') + @tag('posix', '1900') + def test_ticks2datetime_before_1900(self): + ticks = -2209075200000 + date = ticks2datetime(ticks) + self.assertEqual(ustrftime(date, '%Y-%m-%d'), u'1899-12-31') + class MxDateTC(DateTC): datecls = mxDate |