16

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?

Community
  • 1
  • 1
c00kiemonster
  • 20,805
  • 33
  • 89
  • 129
  • 1
    The script that this is intended for spits out very nicely formatted pdfs, and I think it's not that visually appealing with the leading zeros. Not exactly a show stopper, but I'd love to figure out a quick way to avoid them... – c00kiemonster Feb 22 '10 at 09:23

4 Answers4

22

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
Anurag Uniyal
  • 81,711
  • 39
  • 167
  • 215
  • 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)` – Robert Johnstone Sep 19 '12 at 16:49
8

@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
  • 307,646
  • 55
  • 250
  • 337
  • There is now a better solution with Python 3: ```datetime.strptime("05/13/1999", "%m/%d/%Y").strftime("%m/%-d/%Y")``` – bones225 Jan 29 '20 at 03:06
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')))
Tim Pietzcker
  • 313,408
  • 56
  • 485
  • 544
  • 2
    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 Feb 22 '10 at 09:24
  • Well, you could `split` the string, `lstrip` the zeroes, and re-`join` the string, but that's probably much harder to read. – Tim Pietzcker Feb 22 '10 at 09:26
  • 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 Aug 27 '10 at 17:17
2
>>> 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
  • 27,610
  • 7
  • 49
  • 53