【发布时间】:2011-11-28 22:50:09
【问题描述】:
如果我有一个 datetime 对象,我如何将日期作为以下格式的字符串获取:
1/27/1982 # it cannot be 01/27/1982 as there can't be leading 0's
我目前的做法是对所有数字(01、02、03 等)进行 .replace,但这似乎非常低效且麻烦。有什么更好的方法来实现这一点?
谢谢。
【问题讨论】:
标签: python
如果我有一个 datetime 对象,我如何将日期作为以下格式的字符串获取:
1/27/1982 # it cannot be 01/27/1982 as there can't be leading 0's
我目前的做法是对所有数字(01、02、03 等)进行 .replace,但这似乎非常低效且麻烦。有什么更好的方法来实现这一点?
谢谢。
【问题讨论】:
标签: python
你可以自己格式化而不是使用strftime:
'{0}/{1}/{2}'.format(d.month, d.day, d.year) // Python 2.6+
'%d/%d/%d' % (d.month, d.day, d.year)
【讨论】:
'{0.month}/{0.day}/{0.year}'.format(d)
%Y-%m-%d),因为这是唯一明确的顺序。
datetime 对象有一个方法 strftime()。这将使您更灵活地使用内置格式字符串。
http://docs.python.org/library/datetime.html#strftime-and-strptime-behavior.
我已使用lstrip('0') 删除前导零。
>>> 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'
【讨论】: