在 Windows 中使用 Python 获取日期格式

2024-02-14

在给我的作业示例代码中,出现了这一行:

date_format = locale.nl_langinfo(locale.D_FMT)

但在 Windows 中,该行返回以下错误:

File "C:\Users\Shadark\Dropbox\IHM\P3\p3_files\www\cgi-bin\todolist.py", line 11, in <module>
date_format = locale.nl_langinfo(locale.D_FMT)
AttributeError: 'module' object has no attribute 'nl_langinfo'

我读过有关使用语言环境转换但我只读到它被使用的货币或数字。对于我的代码示例或其他类型的功能的用途有什么想法吗?

提前致谢。


你的问题可能是这样的事实locale.nl_langinfo似乎在 Windows Python 2.7.x 中不可用(我在 Windows 64 位 Python 2.7.3 的副本中没有看到它)。查看文档http://docs.python.org/2.7/library/locale.html#locale.nl_langinfo http://docs.python.org/2.7/library/locale.html#locale.nl_langinfo,他们具体说:

此功能并非在所有系统上都可用,并且可能的选项集也可能因平台而异。

一旦你设置了区域设置,类似于:

locale.setlocale(locale.LC_ALL, 'english')

然后调用 some_date.strftime() 将使用正确的区域设置特定格式和字符串。因此,如果您想要字符串格式的日期,请调用some_date.strftime('%x')更换%x with %X为了时间或%c对彼此而言。记录了 strftime 格式的完整列表here http://docs.python.org/2.7/library/datetime.html#strftime-and-strptime-behavior.

>>> d = datetime.datetime.now()
... for loc in ('english', 'german', 'french'):
...     locale.setlocale(locale.LC_ALL, loc)
...     print loc, d.strftime('%c -- %x -- %X -- %B -- %A')
english 11/15/2012 4:10:56 PM -- 11/15/2012 -- 4:10:56 PM -- November -- Thursday
german 15.11.2012 16:10:56 -- 15.11.2012 -- 16:10:56 -- November -- Donnerstag
french 15/11/2012 16:10:56 -- 15/11/2012 -- 16:10:56 -- novembre -- jeudi
14: 'French_France.1252'
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在 Windows 中使用 Python 获取日期格式 的相关文章

随机推荐