python - 如何在 strptime 中使用俄语日期字符串

标签 python encoding

我用 python 解析 html 并且有日期字符串:[ 24-Янв-17 07:24 ]。 “Янв”是“一月”。我想将它转换成日期时间对象。

# Some beautifulsoup parsing
timeData = data.find('div', {'id' : 'time'}).text

import locale
locale.setlocale(locale.LC_TIME, 'ru_RU.UTF-8')
result = datetime.datetime.strptime(timeData, u'[ %d-%b-%y  %H:%M ]')

错误是:

ValueError: time data '[ 24-\xd0\xaf\xd0\xbd\xd0\xb2-17 07:24 ]' does not match format '[ %d-%b-%y %H:%M ]'

type(timeData) 返回 unicode。从 utf-8 编码 timeData 返回 UnicodeEncodeError。怎么了?


chardet 返回 {'confidence': 0.87625, 'encoding': 'utf-8'} 当我写的时候:datetime.datetime.strptime(timeData.encode('utf- 8'), ...) 返回错误如上。


原始页面有 window-1251 编码。

print type(timeData)
print timeData


timeData = timeData.encode('cp1251')
print type(timeData)
print timeData

返回

<type 'unicode'>
[ 24-Янв-17 07:24 ]
<type 'str'>
[ 24-???-17 07:24 ]

最佳答案

快速修复

明白了! янв 在 CPython 2.7.12 中必须是小写。代码(适用于 cygwin 上的 CPy 2.7.12 和 CPy 3.4.5):

# coding=utf8
#timeData='[ 24-Янв-17 07:24 ]'
timeData='[ 24-янв-17 07:24 ]'    ### lower-case
import datetime
import locale
locale.setlocale(locale.LC_TIME, 'ru_RU.UTF-8')
result = datetime.datetime.strptime(timeData, u'[ %d-%b-%y  %H:%M ]')
print(result)

结果:

2017-01-24 07:24:00

如果我使用大写的 Янв,它在 Py 3 中有效,但在 Py 2 中它给出

ValueError: time data '[ 24-\xd0\xaf\xd0\xbd\xd0\xb2-17 07:24 ]' does not match format '[ %d-%b-%y  %H:%M ]'

一般情况

一般在 Python 2 中处理这个问题,小写优先(参见 this answer ):

# coding=utf8
timeData=u'[ 24-Янв-17 07:24 ]'
       # ^ unicode data
import datetime
import locale
locale.setlocale(locale.LC_TIME, 'ru_RU.UTF-8')
print(timeData.lower())     # works OK
result = datetime.datetime.strptime(
    timeData.lower().encode('utf8'), u'[ %d-%b-%y  %H:%M ]')
    ##               ^^^^^^^^^^^^^^ back to a string
    ##       ^^^^^^^ lowercase
print(result)

结果:

[ 24-янв-17 07:24 ]
2017-01-24 07:24:00

我无法用你的 beautifulsoup 代码测试它,但是,一般来说,获取 Unicode 数据,然后使用上面的。

或者,如果可能的话,切换到 Python 3 :)。

解释

那我是怎么想出来的呢?我在 CPython 源代码中寻找 strptime ( search ) 的代码。我找到了方便的 _strptime模块,包含 class LocaleTime .我还找到了一个 mention LocaleTime。要打印可用的月份名称,请执行此操作(添加到上面“快速修复”下代码的末尾):

from _strptime import LocaleTime
lt = LocaleTime()
print(lt.a_month)    

a_month 具有每个 the source 的缩写月份名称.

在 Py3 上,产生:

['', 'янв', 'фев', 'мар', 'апр', 'май', 'июн', 'июл', 'авг', 'сен', 'окт', 'ноя', 'дек']
      ^ lowercase!

在 Py2 上,产生:

['', '\xd1\x8f\xd0\xbd\xd0\xb2',

还有更多。请注意,第一个字符是 \xd1\x8f,在您的错误消息中,\xd0\xaf 不匹配。

关于python - 如何在 strptime 中使用俄语日期字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41839678/

相关文章:

python - Django的模板语言不能安全的处理dict

python - Tensorflow "know"何时不将数据放入 GPU?

python - 找不到麻线(-bash : twine: command not found)

Ruby:如何自动添加 "# encoding: UTF-8"?

html - 为什么 html 转义 >159?

python - 安装 Python 3.5.2,但为 Python 2.6 安装 pip

java - HTTPURLConnection Java header 中的 UTF-8 字符

javascript - 连接具有不同编码的 javascript 文件

ios - NSDictionary objectForKey : string issue

python - 如何将此 shell 代码字符串转换为整数