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'
Python strftime - date without leading 0?
Answer #1: Actually I had the same problem and I realized that, if you add a hyphen between the % and the letter, you can remove the leading zero. For example %Y/%-m/%-d . This only works on Unix (Linux, OS X), not Windows (including Cygwin). On Windows, you would use # , e.g. %Y/%#m/%#d .
strptime is short for "parse time" where strftime is for "formatting time". That is, strptime is the opposite of strftime though they use, conveniently, the same formatting specification.
The day of the month. Single-digit days will have a leading zero. The abbreviated name of the day of the week.
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
@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'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With