Get rid of leading zeros for date strings in Python?

c00kiemonster picture c00kiemonster · Feb 22, 2010 · Viewed 9.6k times · Source

Is there a nimble way to get rid of leading zeros for date strings in Python?

In the example below I'd like to get 12/1/2009 in return instead of 12/01/2009. I guess I could use regular expressions. But to me that seems like overkill. Is there a better solution?

>>> time.strftime('%m/%d/%Y',time.strptime('12/1/2009', '%m/%d/%Y'))
'12/01/2009'

See also

Python strftime - date without leading 0?

Answer

Anurag Uniyal picture Anurag Uniyal · Feb 22, 2010

A simpler and readable solution is to format it yourself:

>>> d = datetime.datetime.now()
>>> "%d/%d/%d"%(d.month, d.day, d.year)
4/8/2012