在Matplotlib DateFormatter中去除时间前导零
如果我使用Matplotlib的日期格式化工具,像这样:
mydateformatter = DateFormatter("%b %d %I:%M %p", self._tz)
我得到的日期会是这样的(注意时间部分有个前导零):
2011年11月27日 03:00 PM
不过,我想把时间的前导零去掉(这样看起来更自然),变成:
2011年11月27日 3:00 PM
有没有办法做到这一点呢?
1 个回答
6
注意:请查看编辑历史,以了解下面评论中的讨论。这篇文章已经根据这些讨论进行了重写。
使用标准的日期转换符是无法做到的,这些转换符在Python文档中有列出(和C语言的标准是一样的)。不过,可能有一些依赖于平台的方法可以实现这种格式。下面这段代码可能会对你有帮助:
# Set the default spec to use -- uglier is better than broken.
hour_fmt = '%I'
# If we're running on a platform that has an hour spec w/o leading zero
# then use that one instead.
if sys.platform.startswith('linux'):
hour_fmt = '%l'
elif sys.platform.startswith('win'):
hour_fmt = '%#I'
# etc
mydateformatter = DateFormatter("%b %d " + hour_fmt + ":%M %p", self._tz)
我已经确认在Linux上%l
可以正常工作,而提问者也确认在Windows上%#I
可以正常工作。