如何确定编码日期时间.strftime(…)在Python中?

2024-05-14 14:11:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我想创建一个“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文档中找不到关于datetime的具体细节。在

另一个这样的帖子提到了语言环境.getlocale(),但这对我来说是回报(没有,没有)。在

如何在运行时可靠地发现Python日期字符串的编码?在


Tags: 字符串程序区域编码datetimedate字节时间
2条回答

在cpython2.7中,datetime.date.strftimetime.strftime的包装器,它又是posix ^{}的包装器。原则上,这取决于LC_TIME的语言环境类别。因此,您需要的是:

import locale
def date_format_encoding():
    return locale.getlocale(locale.LC_TIME)[1] or locale.getpreferredencoding()

以下是datetime.date.__str__的解构,与编辑问题之前相关。在

在cpython2.7中,datetime.date.__str__是用C实现的,它是:

^{pr2}$

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')

为什么不完全跳过date_strunicode构造函数接受日期对象。在

>>> date_unicode = unicode(date)
>>> date_unicode
u'2013-10-16'

在内部,它调用str(date)。然后解码这些字节。所以这相当于显式地创建字节,然后解码它们,但在我看来,读起来更清晰。而且值得养成使用unicode而不是显式使用str和{}的习惯,因为有些对象将定义一个__unicode__方法,该方法可以返回规范的Unicode表示,而根本不需要经过__str__。日期不会。在

医生说:

For a date d, str(d) is equivalent to d.isoformat().

定义为:

Return a string representing the date in ISO 8601 format, ‘YYYY-MM-DD’. For example, date(2002, 12, 4).isoformat() == '2002-12-04'.

所以这也是ASCII码。如果你的默认编码不能解码ASCII,你就必须学会如何处理这种情况。在

相关问题 更多 >

    热门问题