29

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?

Community
  • 1
  • 1
Mathias
  • 6,777
  • 2
  • 20
  • 32
  • 1
    On my Windows build only your first example works without error. The rest result in a `ValueError: Invalid format string`. [This question](http://stackoverflow.com/questions/10807164/python-time-formatting-different-in-windows) may shed some light on yours, regarding standard/portable directives vs. platform-specific "enhancements". – jedwards Mar 06 '15 at 08:14
  • So it depends on the libc implementation of each OS. thank you! Any hints about how/why those examples works generally on unix systems? – Mathias Mar 06 '15 at 10:19

1 Answers1

37

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'
jfs
  • 399,953
  • 195
  • 994
  • 1,670
  • This is great if you are working on Linux. What should you do when working on Windows? – Noctis Skytower Feb 19 '19 at 18:35
  • @NoctisSkytower I guess there wouldn't be the problem on Windows in the first place. If it doesn't support minus in the time format then there won't be the question "why does minus remove anything." No support — no question. – jfs Feb 19 '19 at 18:39
  • 18
    A note to use a `#` instead of a `-` on Windows may be helpful to future readers. – Noctis Skytower Feb 19 '19 at 18:41