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

眉间皱痕 提交于 2019-11-29 17:05:20

问题


This question already has an answer here:

  • Python strftime - date without leading 0? 17 answers

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?


回答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'



回答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



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



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



来源:https://stackoverflow.com/questions/2309828/get-rid-of-leading-zeros-for-date-strings-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!