缩写的月份或星期几,字符串末尾带有 DOT ("." )



我需要用python将许多字符串更改为其他日期时间格式的西班牙语日期格式(DDMMMYYYY,西班牙语缩写为MMM(,但我遇到了问题,因为我的区域设置西班牙语有一个""(adot(,当它将此格式更改为缩写月份格式时。

默认情况下,python采用该语言的英文版本,但我可以使用locale库更改该语言。当我选择'esp'

's_es.utf8'这取决于我的Windows 10的区域设置吗?(我检查了一下,一切似乎都正常(这取决于LOCALE库设置吗?UBUNTU中的相同代码运行正常(无点(

我该如何解决这个问题?

我不想那样变换所有的字符串。。

str_date = str_date[:5] + "." + str_date[5:]

非常感谢!!

示例(之前我更改了语言环境(:

>>> datetime.strptime('2021-01-18', '%Y-%m-%d').strftime('%b')
'ene.'
>>> print(datetime.strptime('18ene2021', '%d%b%Y'))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:UsersgalonsoiAppDataLocalProgramsPythonPython36lib_strptime.py", line 565, in _strptime_datetime
tt, fraction = _strptime(data_string, format)
File "C:UsersgalonsoiAppDataLocalProgramsPythonPython36lib_strptime.py", line 362, in _strptime
(data_string, format))
ValueError: time data '18ene2021' does not match format '%d%b%Y'
>>> print(datetime.strptime('18ene.2021', '%d%b%Y'))
2021-01-18 00:00:00                                       ----> THIS IS OK BECAUSE I WRITE THE DOT AT THE END OF THE ABBREVIATED MONTH

示例的完整序列

>>> import locale
>>> from datetime import datetime
>>>
>>> locale.getlocale()
(None, None)
>>> print (datetime.strptime('2021-01-18', '%Y-%m-%d').strftime('%b'))
Jan
>>> locale.setlocale(locale.LC_ALL, '')
`Spanish_Spain.1252`
>>> locale.getlocale()
(`es_ES`, `cp1252`)
#INCORRECT FORMAT, ADD A "." AT THE END
>>> print (datetime.strptime('2021-01-18', '%Y-%m-%d').strftime('%b'))
ene.
>>> locale.setlocale(locale.LC_ALL, 'es_ES.UTF-8')
`es_ES.UTF-8`
#FORMATO INCORRECTO, AÑADE UN "." a may
>>> print (datetime.strptime('2021-01-18', '%Y-%m-%d').strftime('%b'))
ene.
>>> print(datetime.strptime('18ene2021', '%d%b%Y'))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:UsersgalonsoiAppDataLocalProgramsPythonPython36lib_strptime.py", line 565, in _strptime_datetime
tt, fraction = _strptime(data_string, format)
File "C:UsersgalonsoiAppDataLocalProgramsPythonPython36lib_strptime.py", line 362, in _strptime
(data_string, format))
ValueError: time data '18ene2021' does not match format '%d%b%Y'
>>> print(datetime.strptime('18ene.2021', '%d%b%Y'))
2021-01-18 00:00:00                                       ----> THIS IS OK BECAUSE I WROTE THE DOT AT THE END OF THE ABBREVIATED MONTH

您可以使用dateutil的解析器,在那里您可以通过parser.parserinfo类设置自定义月份名称。例如:

import locale
locale.setlocale(locale.LC_ALL, 'Spanish_Spain.1252') # set locale for reproducibility
import calendar
from dateutil import parser

# subclass parser.parserinfo and set custom month names with dots stripped:
class LocaleParserInfo(parser.parserinfo):
MONTHS = [(ma.strip('.'), ml) for ma, ml in zip(calendar.month_abbr, calendar.month_name)][1:]

s = '18ene2021'
print(parser.parse(s, parserinfo=LocaleParserInfo()))
# 2021-01-18 00:00:00

相关内容

最新更新