summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorAdrien Di Mascio <Adrien.DiMascio@logilab.fr>2011-03-28 15:00:20 +0200
committerAdrien Di Mascio <Adrien.DiMascio@logilab.fr>2011-03-28 15:00:20 +0200
commitf5c44cc62b240848f38618448c8eeb549ad54c79 (patch)
treefd934e6bedc08f56dcfc53ec35508d63fee89eac
parentf334e2088d11bf25e7180b136a2d73fb8c0ea7c6 (diff)
downloadlogilab-common-f5c44cc62b240848f38618448c8eeb549ad54c79.tar.gz
[dates] provide a somewhat reasonable workaround for ticks2datetime where year < 1900
-rw-r--r--date.py15
-rw-r--r--test/unittest_date.py11
2 files changed, 23 insertions, 3 deletions
diff --git a/date.py b/date.py
index 6fa470d..16d76f0 100644
--- a/date.py
+++ b/date.py
@@ -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