You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Windows10+Python3.10中calendar模块locale设置不支持错误求助

解决Windows 10 + Python 3.10下calendar模块的locale.Error问题

问题场景

在Windows 10 + Python 3.10环境中,首次使用calendar模块时触发locale.Error: unsupported locale setting错误,即使调整locale设置后问题仍未解决。

原始代码

import locale
locale.setlocale(locale.LC_ALL, 'de_DE')
print(locale.getlocale())

import calendar

kalenderblatt = calendar.LocaleTextCalendar(calendar.MONDAY)
ausgabe = kalenderblatt.formatmonth(12,2022)
print(ausgabe)

报错输出

('de_DE', 'ISO8859-1')
Traceback (most recent call last):
  File "C:\DATA\Python\Kurs\halloWelt.py", line 533, in <module>
    ausgabe = kalenderblatt.formatmonth(12,2022)
  File "C:\Users\HP\AppData\Local\Programs\Python\Python310\lib\calendar.py", line 360, in formatmonth
    s = self.formatmonthname(theyear, themonth, 7 * (w + 1) - 1)
  File "C:\Users\HP\AppData\Local\Programs\Python\Python310\lib\calendar.py", line 579, in formatmonthname
    with different_locale(self.locale):
  File "C:\Users\HP\AppData\Local\Programs\Python\Python310\lib\calendar.py", line 554, in __enter__
    _locale.setlocale(_locale.LC_TIME, self.locale)
  File "C:\Users\HP\AppData\Local\Programs\Python\Python310\lib\locale.py", line 620, in setlocale
    return _setlocale(category, locale)
locale.Error: unsupported locale setting

已尝试无效操作

将locale.setlocale(locale.LC_ALL, 'de_DE')改为locale.setlocale(locale.LC_ALL, ''),仍出现相同错误。

解决方案

Windows系统的locale命名规则与类Unix系统不同,不能直接使用de_DE这类缩写,需要使用系统识别的完整区域名称,同时注意formatmonth的参数顺序:

方式1:使用Windows标准德语区域名称

import locale
# Windows下德语(德国)的标准locale名称为 'German_Germany.1252'
locale.setlocale(locale.LC_ALL, 'German_Germany.1252')
print(locale.getlocale())

import calendar

# 初始化时指定对应locale
kalenderblatt = calendar.LocaleTextCalendar(calendar.MONDAY, locale='German_Germany.1252')
# formatmonth参数顺序为「年份在前,月份在后」,修正原始代码的参数顺序问题
ausgabe = kalenderblatt.formatmonth(2022, 12)
print(ausgabe)

方式2:使用UTF-8编码的德语区域

如果系统支持UTF-8编码的德语环境,可尝试:

import locale
locale.setlocale(locale.LC_ALL, 'de_DE.UTF-8')
print(locale.getlocale())

import calendar

kalenderblatt = calendar.LocaleTextCalendar(calendar.MONDAY, locale='de_DE.UTF-8')
ausgabe = kalenderblatt.formatmonth(2022, 12)
print(ausgabe)

额外排查技巧

可通过以下代码查看Windows系统支持的所有locale映射,确认目标语言的正确名称:

import locale
print(locale.windows_locale)

内容的提问来源于stack exchange,提问作者Malta

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 16:45:34