ustrftime: ask the system for the encoding instead of trying to guess

strftime uses the encoding corresponding to the LC_TIME locale setting.

Closes #109740

authorJulien Cristau <julien.cristau@logilab.fr>
changeset97da24fddab9
branchstable
phasepublic
hiddenno
parent revision#37af2ea6d6b6 [registry] add assertion useful if e.g. arguments are inversed by inadvertance
child revision#bd15ee92a347 python3: fix code and test so most tests go green. Partially closes #104047
files modified by this revision
ChangeLog
date.py
# HG changeset patch
# User Julien Cristau <julien.cristau@logilab.fr>
# Date 1352789224 -3600
# Tue Nov 13 07:47:04 2012 +0100
# Branch stable
# Node ID 97da24fddab90385fefb44d522760fb67cb6e3ae
# Parent 37af2ea6d6b65c6032336a63d5e4e39455b7d15e
ustrftime: ask the system for the encoding instead of trying to guess

strftime uses the encoding corresponding to the LC_TIME locale setting.

Closes #109740

diff --git a/ChangeLog b/ChangeLog
@@ -1,11 +1,12 @@
1  ChangeLog for logilab.common
2  ============================
3 
4 -	--
5 -    * fix logilab.common.date.ustrftime() for python3 (closes #82161,
6 -      patch by Arfrever Frehtes Taifersar Arahesis)
7 +--
8 +    * date: fix ustrftime() impl. for python3 (closes #82161, patch by Arfrever
9 +      Frehtes Taifersar Arahesis) and encoding detection for python2 (closes
10 +      #109740)
11 
12  2012-07-30  --  0.58.2
13      * modutils: fixes (closes #100757 and #100935)
14 
15 
diff --git a/date.py b/date.py
@@ -21,11 +21,11 @@
16  __docformat__ = "restructuredtext en"
17 
18  import math
19  import re
20  import sys
21 -from locale import getpreferredencoding
22 +from locale import getlocale, LC_TIME
23  from datetime import date, time, datetime, timedelta
24  from time import strptime as time_strptime
25  from calendar import monthrange, timegm
26 
27  try:
@@ -279,20 +279,18 @@
28      return date(somedate.year, somedate.month, days_in_month(somedate))
29 
30  def ustrftime(somedate, fmt='%Y-%m-%d'):
31      """like strftime, but returns a unicode string instead of an encoded
32      string which may be problematic with localized date.
33 -
34 -    When using Python 2, encoding is guessed by locale.getpreferredencoding().
35      """
36      if sys.version_info >= (3, 3):
37          # datetime.date.strftime() supports dates since year 1 in Python >=3.3.
38          return somedate.strftime(fmt)
39      else:
40          try:
41              if sys.version_info < (3, 0):
42 -                encoding = getpreferredencoding(do_setlocale=False) or 'UTF-8'
43 +                encoding = getlocale(LC_TIME)[1] or 'ascii'
44                  return unicode(somedate.strftime(str(fmt)), encoding)
45              else:
46                  return somedate.strftime(fmt)
47          except ValueError, exc:
48              if somedate.year >= 1900: