我在Python中看到了很多关于将日期字符串转换为datetime对象的内容,但我想采用另一种方式。 我有

datetime.datetime(2012, 2, 23, 0, 0)

我想把它转换成'2/23/2012'这样的字符串。


当前回答

通过直接使用datetime对象的组件,可以将datetime对象转换为字符串。

from datetime import date  

myDate = date.today()    
#print(myDate) would output 2017-05-23 because that is today
#reassign the myDate variable to myDate = myDate.month 
#then you could print(myDate.month) and you would get 5 as an integer
dateStr = str(myDate.month)+ "/" + str(myDate.day) + "/" + str(myDate.year)    
# myDate.month is equal to 5 as an integer, i use str() to change it to a 
# string I add(+)the "/" so now I have "5/" then myDate.day is 23 as
# an integer i change it to a string with str() and it is added to the "5/"   
# to get "5/23" and then I add another "/" now we have "5/23/" next is the 
# year which is 2017 as an integer, I use the function str() to change it to 
# a string and add it to the rest of the string.  Now we have "5/23/2017" as 
# a string. The final line prints the string.

print(dateStr)  

产出——> 5/23/2017

其他回答

你可以使用简单的字符串格式化方法:

>>> dt = datetime.datetime(2012, 2, 23, 0, 0)
>>> '{0.month}/{0.day}/{0.year}'.format(dt)
'2/23/2012'
>>> '%s/%s/%s' % (dt.month, dt.day, dt.year)
'2/23/2012'

您可以将datetime转换为字符串。

published_at = "{}".format(self.published_at)

你可以使用strftime来帮助你格式化你的日期。

例如,

import datetime
t = datetime.datetime(2012, 2, 23, 0, 0)
t.strftime('%m/%d/%Y')

将收益率:

'02/23/2012'

关于格式的更多信息请参见这里

另一个选择:

import datetime
now=datetime.datetime.now()
now.isoformat()
# ouptut --> '2016-03-09T08:18:20.860968'

字符串连接str.join可用于构建字符串。

d = datetime.now()
'/'.join(str(x) for x in (d.month, d.day, d.year))
'3/7/2016'