在具有 BST 时区的 Windows 上使用 python datetime.datetime.strptime
我需要解析许多不同格式的许多不同日期。我在以下方面遇到困难,想知道是否有人可以解释原因;
以下内容适用于 Linux 系统:
from datetime import datetime
datetime.strptime('Tue 23 Aug 2011 09:00:07 PM BST','%a %d %b %Y %H:%M:%S %p %Z')
但在 Windows 下运行会引发
ValueError: time data does not match format
但是,如果我在 Windows 上尝试 GMT 而不是 BST,它工作正常;
from datetime import datetime
datetime.strptime('Tue 23 Aug 2011 09:00:07 PM GMT','%a %d %b %Y %H:%M:%S %p %Z')
python 在 Windows 下不理解 BST 时区,但在 Linux 下工作正常,有什么原因吗?
谢谢,
马特。
I need to parse many different dates in many different formats. I am having trouble with the following and wondered if anyopne could explain why;
The following works on a linux system:
from datetime import datetime
datetime.strptime('Tue 23 Aug 2011 09:00:07 PM BST','%a %d %b %Y %H:%M:%S %p %Z')
But running under windows it raises
ValueError: time data does not match format
However, if I try GMT not BST on windows, it works fine;
from datetime import datetime
datetime.strptime('Tue 23 Aug 2011 09:00:07 PM GMT','%a %d %b %Y %H:%M:%S %p %Z')
Is there a reason python does not understand the BST timezone under windows, but it works fine under Linux?
thanks,
Matt.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在我看来,像这样解析三个字母的时区代码不是一个好的做法(当然除非你别无选择)。例如,“EST”在美国常用来表示 UTC-4/5,在澳大利亚也常用。因此,对“EST”的任何支持都必须依赖于语言环境。如果“BST”同样含糊不清,我也不会感到惊讶。
我强烈建议使用
pytz
模块,其中英国民用时间是给定字符串标识符Europe/London
,UTC 称为Etc/UTC
。无论运行应用程序的用户或系统的区域设置如何,pytz
API 都将提供一致的结果。如果您正在开发必须与语言环境相关的 UI,或者使用无法更改的格式解析输入,请考虑使用
pytz
时区对象的缩写字典。例如:{'BST': '欧洲/伦敦'}
。然后您的应用程序可以统一使用 UTC 日期和时间,这将大大减少出错的可能性。In my opinion, parsing a three-letter time zone code like this is not a good practice (unless of course you have no choice). For example, "EST" is commonly used in the USA for UTC-4/5 and is also commonly used in Australia. So any support for "EST" must therefore be dependent on locale. It would not surprise me if "BST" was similarly ambiguous.
I highly recommend using the
pytz
module in which British civil time is given the string identifierEurope/London
and UTC is calledEtc/UTC
. Thepytz
API will give consistent results regardless of the locale of the user or system running the application.If you are working on a UI that must be tied to locale, or parsing inputs with formats you cannot change, then consider using a dictionary of abbreviations to
pytz
timezone objects. For example:{'BST': 'Europe/London'}
. Then your application can work with UTC dates and times uniformly, which will greatly reduce the possibility of errors.