Get rid of leading zeros for date strings in Python?

10,040

Solution 1

@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 2

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 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.

Share:
10,040
c00kiemonster
Author by

c00kiemonster

Updated on June 11, 2022

Comments

  • c00kiemonster
    c00kiemonster almost 2 years

    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?

  • c00kiemonster
    c00kiemonster about 14 years
    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...
  • Tim Pietzcker
    Tim Pietzcker about 14 years
    Well, you could split the string, lstrip the zeroes, and re-join the string, but that's probably much harder to read.
  • John La Rooy
    John La Rooy about 14 years
    Yeah, it does depend on the system's strftime. Doesn't work on Python2.6.1+WinXP for example
  • Nick Farina
    Nick Farina over 13 years
    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!
  • Robert Johnstone
    Robert Johnstone over 11 years
    took me ages to find the answer to this particular problem. I'm having to pass my date to the date class, and it only accepts date(d,m,yyyy) not date(dd,mm,yyyy)
  • bones225
    bones225 about 4 years
    There is now a better solution with Python 3: datetime.strptime("05/13/1999", "%m/%d/%Y").strftime("%m/%-d/%Y")