开发者

Remove leading 0's for str(date) [duplicate]

This question already has answers here: Python strftime - date without leading 0? (21 answers) Closed 5 years ago.

If I have a datetime object, how would I get the date as a string in the following format:

1/27/1982  # it cannot be 01/27/1982 as there can't b开发者_StackOverflow社区e leading 0's

The current way I'm doing it is doing a .replace for all the digits (01, 02, 03, etc...) but this seems very inefficient and cumbersome. What would be a better way to accomplish this?


You could format it yourself instead of using strftime:

'{0}/{1}/{2}'.format(d.month, d.day, d.year) // Python 2.6+

'%d/%d/%d' % (d.month, d.day, d.year)


The datetime object has a method strftime(). This would give you more flexibility to use the in-built format strings.

http://docs.python.org/library/datetime.html#strftime-and-strptime-behavior.

I have used lstrip('0') to remove the leading zero.

>>> d = datetime.datetime(1982, 1, 27)

>>> d.strftime("%m/%d/%y")
'01/27/82'

>>> d.strftime("%m/%d/%Y")
'01/27/1982'

>>> d.strftime("%m/%d/%Y").lstrip('0')
'1/27/1982'
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜