Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
259 views
in Technique[技术] by (71.8m points)

python - Why does "%-d", or "%-e" remove the leading space or zero?

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.

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'

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

The result on my Ubuntu machine:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...