Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get rid of leading zeros for date strings in Python? [duplicate]

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?

like image 329
c00kiemonster Avatar asked Feb 22 '10 09:02

c00kiemonster


People also ask

How do you remove leading zeros from a date in Python?

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 .

What is Strftime and Strptime in Python?

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.

Should dates have leading zeros?

The day of the month. Single-digit days will have a leading zero. The abbreviated name of the day of the week.


2 Answers

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
like image 197
Anurag Uniyal Avatar answered Oct 13 '22 00:10

Anurag Uniyal


@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'
like image 26
ghostdog74 Avatar answered Oct 13 '22 00:10

ghostdog74