Using dateutil.parser to parse a date in another language(使用 dateutil.parser 解析另一种语言的日期)
问题描述
Dateutil 是解析字符串格式日期的好工具.例如
Dateutil is a great tool for parsing dates in string format. for example
from dateutil.parser import parse
parse("Tue, 01 Oct 2013 14:26:00 -0300")
返回
datetime.datetime(2013, 10, 1, 14, 26, tzinfo=tzoffset(None, -10800))
然而,
parse("Ter, 01 Out 2013 14:26:00 -0300") # In portuguese
产生此错误:
ValueError: unknown string format
有人知道如何让 dateutil 了解语言环境吗?
Does anybody know how to make dateutil aware of the locale?
推荐答案
据我所知,dateutil 不支持区域设置(还没有!).
As far as I can see, dateutil is not locale aware (yet!).
我能想到三个替代建议:
I can think of three alternative suggestions:
日期和月份名称在
dateutil.parser中硬编码(作为parserinfo类的一部分).您可以将 parserinfo 子类化,并将这些名称替换为葡萄牙语的适当名称.
The day and month names are hardcoded in
dateutil.parser(as part of theparserinfoclass). You could subclass parserinfo, and replace these names with the appropriate names for Portuguese.
修改 dateutil 以根据用户的区域设置获取日期和月份名称.所以你可以做类似的事情
Modify dateutil to get day and month names based on the user’s locale. So you could do something like
import locale
locale.setlocale(locale.LC_ALL, "pt_PT")
from dateutil.parser import parse
parse("Ter, 01 Out 2013 14:26:00 -0300")
我已经启动了一个分支,它从 calendar 模块(可识别区域设置)中获取名称来处理这个问题:https://github.com/alexwlchan/dateutil
I’ve started a fork which gets the names from the calendar module (which is locale-aware) to work on this: https://github.com/alexwlchan/dateutil
现在它适用于葡萄牙语(或似乎适用),但我想在向主分支提交补丁之前再考虑一下.特别是,如果它面对西欧语言中没有使用的字符,可能会发生怪异.我还没有测试过这个.(参见https://stackoverflow.com/a/8917539/1558022)
Right now it works for Portuguese (or seems to), but I want to think about it a bit more before I submit a patch to the main branch. In particular, weirdness may happen if it faces characters which aren’t used in Western European languages. I haven’t tested this yet. (See https://stackoverflow.com/a/8917539/1558022)
如果你没有绑定到 dateutil 模块,你可以使用 datetime 代替,它已经是语言环境感知的:
If you’re not tied to the dateutil module, you could use datetime instead, which is already locale-aware:
from datetime import datetime, date
import locale
locale.setlocale(locale.LC_ALL, "pt_PT")
datetime.strptime("Ter, 01 Out 2013 14:26:00 -0300",
"%a, %d %b %Y %H:%M:%S %z")
(请注意,%z 令牌在日期时间中始终不受支持.)
这篇关于使用 dateutil.parser 解析另一种语言的日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:使用 dateutil.parser 解析另一种语言的日期
基础教程推荐
- 无法导入 Pytorch [WinError 126] 找不到指定的模块 2022-01-01
- 求两个直方图的卷积 2022-01-01
- 修改列表中的数据帧不起作用 2022-01-01
- 使用大型矩阵时禁止 Pycharm 输出中的自动换行符 2022-01-01
- 在Python中从Azure BLOB存储中读取文件 2022-01-01
- 包装空间模型 2022-01-01
- Plotly:如何设置绘图图形的样式,使其不显示缺失日期的间隙? 2022-01-01
- 在同一图形上绘制Bokeh的烛台和音量条 2022-01-01
- PANDA VALUE_COUNTS包含GROUP BY之前的所有值 2022-01-01
- PermissionError: pip 从 8.1.1 升级到 8.1.2 2022-01-01
