Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 628
Mathias Avatar asked Mar 06 '15 07:03

Mathias


People also ask

What does Strptime mean?

DESCRIPTION. The strptime() function converts the character string pointed to by buf to values which are stored in the tm structure pointed to by tm, using the format specified by format. The format is composed of zero or more directives.

What is the difference between Strptime and Strftime?

strptime is short for "parse time" where strftime is for "formatting time". That is, strptime is the opposite of strftime though they use, conveniently, the same formatting specification.

How does Strptime work?

The strptime() function in Python is used to format and return a string representation of date and time. It takes in the date, time, or both as an input, and parses it according to the directives given to it. It raises ValueError if the string cannot be formatted according to the provided directives.

How do I remove 0 from a date in python?

Your answerIf you add a hyphen between the % and the letter, you can remove the leading zero. For example %Y/%-m/%-d. This only works on Unix (Linux, OS X), not Windows. On Windows, you would use #, e.g. %Y/%#m/%#d.


1 Answers

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' 
like image 182
jfs Avatar answered Nov 03 '22 00:11

jfs