Skip to content Skip to sidebar Skip to footer

Get Rid Of Leading Zeros For Date Strings In Python?

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 re

Solution 1:

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

Solution 2:

@OP, it doesn't take much to do a bit of string manipulation.

>>>t=time.strftime('%m/%d/%Y',time.strptime('12/1/2009', '%m/%d/%Y'))>>>'/'.join( map( str, map(int,t.split("/")) ) )
'12/1/2009'

Solution 3:

I'd suggest a very simple regular expression. It's not like this is performace-critical, is it?

Search for \b0 and replace with nothing.

I. e.:

import re
newstring = re.sub(r"\b0","",time.strftime('%m/%d/%Y',time.strptime('12/1/2009', '%m/%d/%Y')))

Solution 4:

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

However, I suspect this is dependent on the system's strftime() implementation and might not be fully portable to all platforms, if that matters to you.

Post a Comment for "Get Rid Of Leading Zeros For Date Strings In Python?"