Felipe Maion
Felipe Maion

Reputation: 351

Problem converting str to date in python when locale is set to pt-Br

Here is a snippet of my code:

import locale
from datetime import datetime

locale.setlocale(locale.LC_ALL, "pt-BR") # Windows

#### doing stuff with locale (like converting number 1.000,00)
#####

date_str = '29/12/2017' # The date - 29 Dec 2017
format_str = '%d/%m/%Y' # The format


datetime_obj = datetime.strptime(date_str, format_str)

with only this small code I get the following error:


ValueError
Traceback (most recent call last) in () 11 12 ---> 13 datetime_obj = datetime.strptime(date_str, format_str)

~\AppData\Local\Continuum\anaconda3\lib_strptime.py in () 278 # DO NOT modify _TimeRE_cache or _regex_cache without acquiring the cache lock 279 # first! --> 280 _TimeRE_cache = TimeRE() 281 _CACHE_MAX_SIZE = 5 # Max number of regexes stored in _regex_cache 282 _regex_cache = {}

~\AppData\Local\Continuum\anaconda3\lib_strptime.py in init(self, locale_time) 192 self.locale_time = locale_time 193 else: --> 194 self.locale_time = LocaleTime() 195 base = super() 196 base.init({

~\AppData\Local\Continuum\anaconda3\lib_strptime.py in init(self) 70 71 """ ---> 72 self.lang = _getlang() 73 self.__calc_weekday() 74 self.__calc_month()

~\AppData\Local\Continuum\anaconda3\lib_strptime.py in _getlang() 29 def _getlang(): 30 # Figure out what the current language is set to. ---> 31 return locale.getlocale(locale.LC_TIME) 32 33 class LocaleTime(object):

~\AppData\Local\Continuum\anaconda3\lib\locale.py in getlocale(category) 579 if category == LC_ALL and ';' in localename: 580 raise TypeError('category LC_ALL is not supported') --> 581 return _parse_localename(localename) 582 583 def setlocale(category, locale=None):

~\AppData\Local\Continuum\anaconda3\lib\locale.py in _parse_localename(localename) 488 elif code == 'C': 489 return None, None --> 490 raise ValueError('unknown locale: %s' % localename) 491 492 def _build_localename(localetuple):

ValueError: unknown locale: pt-BR

Any clue how to solve this issue?

I am running Windows, Python 3.6.5 |Anaconda, Inc.| (default, Mar 29 2018, 13:32:41) [MSC v.1900 64 bit (AMD64)]

Upvotes: 0

Views: 1707

Answers (2)

Allan Oricil
Allan Oricil

Reputation: 21

On Windows go to

Control Panel -> Clock and Region -> Region -> Administrative (tab) -> Change system locale (Button) -> change the language to Portuguese (Brazil) -> restart the machine

Now on your code set the locale to

locale.setlocale(locale.LC_ALL, 'pt-BR.UTF-8')

I was with the same problem like you. My mistake was the lack of ".UTF-8" on the language name.

Upvotes: 2

Imaduddin A Majid
Imaduddin A Majid

Reputation: 383

Try this

locale.setlocale(locale.LC_ALL, "pt_br")

Upvotes: 2

Related Questions