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

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

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


当前回答

你可以用下面的方法将datetime转换为字符串:

from datetime import datetime

date_time = datetime(2012, 2, 23, 0, 0)
date = date_time.strftime('%m/%d/%Y')
print("date: %s" % date)

以下是一些可以用来将datetime转换为字符串的模式:

为了更好地理解,您可以参考这篇关于如何在Python或官方strftime文档中将字符串转换为datetime和datetime转换为字符串的文章

其他回答

通过直接使用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

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

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

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

d = datetime.now()
'/'.join(str(x) for x in (d.month, d.day, d.year))
'3/7/2016'
end_date = "2021-04-18 16:00:00"
end_date_string = end_date.strftime("%Y-%m-%d")
print(end_date_string)

类型特定的格式也可以使用:

t = datetime.datetime(2012, 2, 23, 0, 0)
"{:%m/%d/%Y}".format(t)

输出:

'02/23/2012'