python - 为什么 "%-d"或 "%-e"删除前导空格或零?

标签 python python-2.7 datetime strftime

关于 SO 问题 904928 (Python strftime - date without leading 0?)瑞恩回答:

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.

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

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

>>> 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 string operations

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

最佳答案

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

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.

Glibc notes for strftime(3) :

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

我的 Ubuntu 机器上的结果:

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

关于python - 为什么 "%-d"或 "%-e"删除前导空格或零?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28894172/

相关文章:

python - 按索引对 Pandas 数据框中两列中的重复行求和

javascript - 在 JavaScript 中解析 Json 数据时出现语法错误

python - 将一行 "if else"语句分成多行

python - 尝试访问 Pandas 系列中的元素时出错

java - ResolverStyle.STRICT 在 `@DateTimeFormat(iso = DateTimeFormat.ISO.DATE)` 中不起作用

python - 在Python中比较同一字典中每个键的字典值

python - 按第一列分组并显示为列

python-2.7 - 图论。如何处理这类问题?我想知道在尝试解决此问题时需要思考的逻辑和方式。

python - 带有 python-firebase 的 Firebase 抛出 "Connection reset by peer"(Celery + gevent 参与)

python - pandas 获取时间戳差异(以毫秒为单位)作为整数