Remove leading 0's for str(date)

Question:

If I have a datetime object, how would I get the date as a string in the following format:

1/27/1982  # it cannot be 01/27/1982 as there can't be leading 0's

The current way I’m doing it is doing a .replace for all the digits (01, 02, 03, etc…) but this seems very inefficient and cumbersome. What would be a better way to accomplish this?

Asked By: David542

||

Answers:

You could format it yourself instead of using strftime:

'{0}/{1}/{2}'.format(d.month, d.day, d.year) // Python 2.6+

'%d/%d/%d' % (d.month, d.day, d.year)
Answered By: bobince

The datetime object has a method strftime(). This would give you more flexibility to use the in-built format strings.

http://docs.python.org/library/datetime.html#strftime-and-strptime-behavior.

I have used lstrip('0') to remove the leading zero.

>>> d = datetime.datetime(1982, 1, 27)

>>> d.strftime("%m/%d/%y")
'01/27/82'

>>> d.strftime("%m/%d/%Y")
'01/27/1982'

>>> d.strftime("%m/%d/%Y").lstrip('0')
'1/27/1982'
Answered By: varunl
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.