我想创建一个“unicode 三明治”,其中包含一些日期/时间值并且与区域设置无关。对于外行,术语 unicode 三明治描述了在程序边界从字节转换为 unicode 并返回的做法,即外部的字节和内部的 unicode。
我看了Ned Batchelder's excellent video on unicode今天早上,我正在尝试转换我的一些代码以与他的明智建议保持一致。
我遇到的问题是我不知道如何确定 str(date)
或其等效项返回的字符串的编码。我的想法是做这样的事情,为了清楚起见有点冗长:
date_str_encoding = some_magical_method_I_have_yet_to_discover()
date = datetime.datetime(2013, 10, 16).date()
date_str = date.strftime('%A %B %d, &Y') # perhaps 'Sábado Octubre 19, 2013'
date_unicode = date_str.decode(date_str_encoding)
Ned 的 unicode “生活事实”之一是“你无法推断字节的编码。你必须被告知或者你必须猜测。”不幸的是,我无法在日期时间的 Python 文档中找到该特定细节。
另一篇 SO 帖子提到了 locale.getlocale() 的使用,但它为我返回了 (None, None)。
如何在运行时可靠地发现 Python 日期字符串的编码?
最佳答案
在 CPython 2.7 中,datetime.date.strftime
是 time.strftime
的包装器,它又是 posix strftime(3)
的包装器.原则上,这取决于 LC_TIME
的语言环境类别。因此,您正在寻找的是:
import locale
def date_format_encoding():
return locale.getlocale(locale.LC_TIME)[1] or locale.getpreferredencoding()
下面是对 datetime.date.__str__
的解构,在编辑问题之前是相关的。
在CPython 2.7中,datetime.date.__str__
是用C实现的,它是:
static PyObject *
date_str(PyDateTime_Date *self)
{
return PyObject_CallMethod((PyObject *)self, "isoformat", "()");
}
datetime.date.isoformat
又在 C 中实现为:
static char *
isoformat_date(PyDateTime_Date *dt, char buffer[], int bufflen)
{
int x;
x = PyOS_snprintf(buffer, bufflen,
"%04d-%02d-%02d",
GET_YEAR(dt), GET_MONTH(dt), GET_DAY(dt));
assert(bufflen >= x);
return buffer + x;
}
基本上,str(datetime.date)
返回的字节绝不会是数字和“-”的 ascii 码以外的任何其他字节。说总是是正确的:
str(my_date).decode('ascii')
关于python - 如何确定 Python 中 datetime.strftime(...) 的编码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19412915/