summaryrefslogtreecommitdiff
path: root/date.py
diff options
context:
space:
mode:
authorAlexandre Fayolle <alexandre.fayolle@logilab.fr>2010-08-23 09:05:49 +0200
committerAlexandre Fayolle <alexandre.fayolle@logilab.fr>2010-08-23 09:05:49 +0200
commite88ea135e3d93f4f1584d14090f43b2cd467c7d7 (patch)
tree8bc0b4aac58141e052af8251789de75fc702dcfd /date.py
parent1facc67b4cc2a0362610e06aac4f764e517023ac (diff)
downloadlogilab-common-e88ea135e3d93f4f1584d14090f43b2cd467c7d7.tar.gz
new ustrftime implementation working around datetime limitaion on dates < 1900
Diffstat (limited to 'date.py')
-rw-r--r--date.py21
1 files changed, 19 insertions, 2 deletions
diff --git a/date.py b/date.py
index bc7b32e..81bbbc7 100644
--- a/date.py
+++ b/date.py
@@ -24,6 +24,7 @@
__docformat__ = "restructuredtext en"
import math
+import re
from locale import getpreferredencoding
from datetime import date, time, datetime, timedelta
from time import strptime as time_strptime
@@ -274,6 +275,22 @@ def ustrftime(somedate, fmt='%Y-%m-%d'):
encoding is guessed by locale.getpreferredencoding()
"""
- # date format may depend on the locale
encoding = getpreferredencoding(do_setlocale=False) or 'UTF-8'
- return unicode(somedate.strftime(str(fmt)), encoding)
+ try:
+ return unicode(somedate.strftime(str(fmt)), encoding)
+ except ValueError, exc:
+ if '1900' not in exc.args[0]:
+ raise
+ # datetime is not happy with dates before 1900
+ # we try to work around this, assuming a simple
+ # format string
+ fields = {'Y': somedate.year,
+ 'm': somedate.month,
+ 'd': somedate.day,
+ }
+ if isinstance(somedate, datetime):
+ fields.update({'H': somedate.hour,
+ 'M': somedate.minute,
+ 'S': somedate.second})
+ fmt = re.sub('%([YmdHMS])', r'%(\1)02d', fmt)
+ return unicode(fmt) % fields