开发者

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

开发者 https://www.devze.com 2022-12-21 01:19 出处:网络
This question already has answers here: Python strftime - date without leading 0? (21 answers) Closed 5 years ago.
This question already has answers here: Python strftime - date without leading 0? (21 answers) Closed 5 years ago.

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 solu开发者_StackOverflowtion?

>>> time.strftime('%m/%d/%Y',time.strptime('12/1/2009', '%m/%d/%Y'))
'12/01/2009'

See also

Python strftime - date without leading 0?


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'


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')))


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

0

精彩评论

暂无评论...
验证码 换一张
取 消