开发者

Why does Python store German and Spanish (and other?) time format strings as %T in the locale module?

开发者 https://www.devze.com 2023-03-31 08:19 出处:网络
I\'m writing a test for a program that will be used in multiple locales. While running the test in German, i got the error

I'm writing a test for a program that will be used in multiple locales. While running the test in German, i got the error

Traceback (most recent call last):
  File "<stdi开发者_如何学JAVAn>", line 1, in <module>
  File "/usr/local/lib/python2.7/_strptime.py", line 454, in _strptime_time
    return _strptime(data_string, format)[0]
  File "/usr/local/lib/python2.7/_strptime.py", line 317, in _strptime
    (bad_directive, format))
ValueError: 'T' is a bad directive in format '%T'

Digging into this, i discovered that using locale.nl_langinfo(locale.T_FMT) while in German or Spanish (and potentially other languages) produces the format string '%T'. This is not recognized in the time module.

The documentation on locale at python.org doesn't mention anything about returning '%T'. The only reference to '%T' i could find anywhere is in a response to a separate StackOverflow question. From that post and context, i'm assuming '%T' is shorthand for '%H:%M:%S'.

My question is, how do i handle the locales for which locale will return '%T' for its format string without doing something like

if fmt_str == '%T':
    fmt_str = '%H:%M:%S'

to handle those cases?


This is a wholly unsatisfying answer, but this is the answer anyway:

The reason locale and time.strptime do not play well together is because the locale formats were not written for time.strptime. They were written for time.strftime, to produce necessary date/time formats, not to parse them.

Because time.strptime was written to be platform independent, it does not accept as many directives as locale gives out; time.strftime needs to be able to convert anything thrown at it, so it accepts any platform-defined directive.

So, no, there is no easier way to make time and locale cooperate the way I want them to.


Actually I see you are using strptime, not strftime. And the documentation for strptime mentions:

Only the directives specified in the documentation are supported. Because strftime() is implemented per platform it can sometimes offer more directives than those listed. But strptime() is independent of any platform and thus does not necessarily support all directives available that are not documented as supported.

As suggested here, you can use a more powerful date parser, like dateutil

>> import dateutil.parser
>> dateutil.parser.parse("Thu Sep 25 10:36:28 2003")
datetime.datetime(2003, 9, 25, 10, 36, 28)
0

精彩评论

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