在Matplotlib DateFormatter中删除一天中的前导零

时间:2012-01-31 18:46:38

标签: python matplotlib

如果我使用Matplotlib DateFormatter,就像这样:

mydateformatter = DateFormatter("%b %d %I:%M %p", self._tz)

我会得到日期(注意时间部分有一个前导零):

2011年11月27日  03:00 PM

相反,我想在时间上失去领先的零(这样更人性化),比如:

2011年11月27日   下午3:00

有办法吗?

1 个答案:

答案 0 :(得分:5)

注意:请参阅编辑记录以了解以下评论中的讨论。这篇文章已被重写以反映它们。

使用标准日期转换说明符无法完成,这些说明符在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)

我已确认%l可以在Linux上工作,并且OP已经确认'%#I`可以在Windows上运行。