简体   繁体   中英

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 understand 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM