views:

658

answers:

4

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'
+1  A: 

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')))
Tim Pietzcker
That's pretty much what I have in place, but as I said in the initial post, I just think it's a bit overkill to use re for such a trivial thing...
c00kiemonster
Well, you could `split` the string, `lstrip` the zeroes, and re-`join` the string, but that's probably much harder to read.
Tim Pietzcker
This is what I ended up with, it results in the cleanest code in my opinion. I'm still shocked that this is so nontrivial though!
Nick Farina
+3  A: 

@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'
ghostdog74
+7  A: 

why not format it yourselves?

import datetime
d = datetime.datetime(2009, 9, 9)
print "%d/%d/%d"%(d.month, d.day, d.year)

output:

9/9/2009
Anurag Uniyal
+1  A: 
>>> 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.

Pär Wieslander
Yeah, it does depend on the system's strftime. Doesn't work on Python2.6.1+WinXP for example
gnibbler