我正在使用标准库中的Python的calendar模块。基本上,我需要一个月所有天的列表,如下所示:
>>> import calendar
>>> calobject = calendar.monthcalendar(2012, 10)
>>> print calobject
[[1, 2, 3, 4, 5, 6, 7], [8, 9, 10, 11, 12, 13, 14], [15, 16, 17, 18, 19, 20, 21], [22, 23, 24, 25, 26, 27, 28], [29, 30, 31, 0, 0, 0, 0]]
现在,我还需要特定区域中月份和日期的名称。我没有找到从calobject
本身获取这些的方法-但我能够像这样获取它们:
>>> import calendar
>>> calobject = calendar.LocaleTextCalendar(calendar.MONDAY, 'de_DE')
>>> calobject.formatmonth(2012, 10)
' Oktober 2012\nMo Di Mi Do Fr Sa So\n 1 2 3 4 5 6 7\n 8 9 10 11 12 13 14\n15 16 17 18 19 20 21\n22 23 24 25 26 27 28\n29 30 31\n'
因此Oktober
是十月的de_DE
名称。精细。信息必须在那里。我想知道是否可以在普通的calendar
对象而不是calendar.LocaleTextCalendar
对象上以某种方式访问该月份的名称。我真正需要的是第一个示例(带有列表),我不喜欢创建两个日历对象以获取本地化名称的想法。
任何人都有一个聪明的主意吗?
python大神给出的解决方案
这来自calendar
模块的源代码:
def formatmonthname(self, theyear, themonth, width, withyear=True):
with TimeEncoding(self.locale) as encoding:
s = month_name[themonth]
if encoding is not None:
s = s.decode(encoding)
if withyear:
s = "%s %r" % (s, theyear)
return s.center(width)
可以从TimeEncoding
模块导入month_name
和calendar
。这提供了以下方法:
from calendar import TimeEncoding, month_name
def get_month_name(month_no, locale):
with TimeEncoding(locale) as encoding:
s = month_name[month_no]
if encoding is not None:
s = s.decode(encoding)
return s
print get_month_name(3, "nb_NO.UTF-8")
对我而言,不需要解码步骤,只需在month_name[3]
上下文中打印TimeEncoding
即可打印“火星”,这对于“三月”来说是挪威语。
对于工作日,有一种使用day_name
和day_abbr
字典的类似方法:
from calendar import TimeEncoding, day_name, day_abbr
def get_day_name(day_no, locale, short=False):
with TimeEncoding(locale) as encoding:
if short:
s = day_abbr[day_no]
else:
s = day_name[day_no]
if encoding is not None:
s = s.decode(encoding)
return s
Python pytz时区函数返回的时区为9分钟 - python由于某些原因,我无法从以下代码中找出原因:>>> from pytz import timezone >>> timezone('America/Chicago') 我得到:<DstTzInfo 'America/Chicago' LMT-1 day, 18:09:00 STD…
Python sqlite3数据库已锁定 - python我在Windows上使用Python 3和sqlite3。我正在开发一个使用数据库存储联系人的小型应用程序。我注意到,如果应用程序被强制关闭(通过错误或通过任务管理器结束),则会收到sqlite3错误(sqlite3.OperationalError:数据库已锁定)。我想这是因为在应用程序关闭之前,我没有正确关闭数据库连接。我已经试过了: connectio…
用大写字母拆分字符串,但忽略AAA Python Regex - python我的正则表达式:vendor = "MyNameIsJoe. I'mWorkerInAAAinc." ven = re.split(r'(?<=[a-z])[A-Z]|[A-Z](?=[a-z])', vendor) 以大写字母分割字符串,例如:'我的名字是乔。 I'mWorkerInAAAinc”变成…
如何打印浮点数的全精度[Python] - python我编写了以下函数,其中传递了x,y的值:def check(x, y): print(type(x)) print(type(y)) print(x) print(y) if x == y: print "Yes" 现在当我打电话check(1.00000000000000001, 1.0000000000000002)它正在打印:<…
Python:检查新文件是否在文件夹中[重复] - pythonThis question already has answers here: How do I watch a file for changes? (23个答案) 3年前关闭。 我是python的新手,但是我尝试创建一个自动化过程,其中我的代码将侦听目录中的新文件条目。例如,某人可以手动将zip文件复制到一个特定的文件夹中,并且我希望我的代码能够在文件完全…