开发者

Using python datetime.datetime.strptime on windows with BST timezone

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 unders开发者_运维技巧tand the BST timezone under windows, but it works fine under Linux?

thanks,

Matt.


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 identifier Europe/London and UTC is called Etc/UTC. The pytz 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜