为什么“%-d”或“%-e”删除前导空格还是零? [英] Why does "%-d", or "%-e" remove the leading space or zero?

查看:188
本文介绍了为什么“%-d”或“%-e”删除前导空格还是零?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在这个问题上, 904928(Python strftime - 没有前导0的日期) Ryan回答:

On SO question 904928 (Python strftime - date without leading 0?) Ryan answered:


其实我也有同样的问题,我意识到,如果你在%和该信件可以删除前导零。

Actually I had the same problem and I realised that, if you add a hyphen between the % and the letter, you can remove the leading zero.

例如%Y /% - m /% - d。

For example %Y/%-m/%-d.

我遇到同样的问题,这是一个很好的解决方案,但是为什么这样做呢?

I faced the same problem and that was a great solution, BUT, why does this behave like this?

>>> import datetime
>>> datetime.datetime(2015, 3, 5).strftime('%d')
'05'

>>> datetime.datetime(2015, 3, 5).strftime('%-d')
'5'

# It also works with a leading space
>>> datetime.datetime(2015, 3, 5).strftime('%e')
' 5'

>>> datetime.datetime(2015, 3, 5).strftime('%-e')
'5'

# Of course other numbers doesn't get stripped
>>> datetime.datetime(2015, 3, 15).strftime('%-e')
'15'

我找不到任何文档? - > python datetime docs / python字符串操作

I cannot find any documentation about that? -> python datetime docs / python string operations

似乎这在Windows机器上不起作用,我不使用Windows,知道为什么它不起作用会很有趣?

It seems like this doesn't work on windows machines, well I don't use windows but it would be interesting to know why it doesn't work?

推荐答案

c $ c> c code> strftime() / code>功能是平台相关的

Python datetime.strftime() delegates to C strftime() function that is platform-dependent:


支持的全套格式代码因平台而异,
因为Python调用平台C库的strftime()函数,而
平台变体是常见的。要查看平台支持的全套格式代码
,请参阅strftime(3)文档。

The full set of format codes supported varies across platforms, because Python calls the platform C library’s strftime() function, and platform variations are common. To see the full set of format codes supported on your platform, consult the strftime(3) documentation.

strftime(3)的Glibc注释


- (破折号)不要填写数字结果字符串。

- (dash) Do not pad a numeric result string.

我的Ubuntu机器上的结果:

The result on my Ubuntu machine:

>>> from datetime import datetime
>>> datetime.now().strftime('%d')
'07'
>>> datetime.now().strftime('%-d')
'7'

这篇关于为什么“%-d”或“%-e”删除前导空格还是零?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆