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 "<stdin>", 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With