我在Python中看到了很多关于将日期字符串转换为datetime对象的内容,但我想采用另一种方式。 我有
datetime.datetime(2012, 2, 23, 0, 0)
我想把它转换成'2/23/2012'这样的字符串。
我在Python中看到了很多关于将日期字符串转换为datetime对象的内容,但我想采用另一种方式。 我有
datetime.datetime(2012, 2, 23, 0, 0)
我想把它转换成'2/23/2012'这样的字符串。
当前回答
另一个选择:
import datetime
now=datetime.datetime.now()
now.isoformat()
# ouptut --> '2016-03-09T08:18:20.860968'
其他回答
你可以用下面的方法将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转换为字符串的文章
字符串连接str.join可用于构建字符串。
d = datetime.now()
'/'.join(str(x) for x in (d.month, d.day, d.year))
'3/7/2016'
类型特定的格式也可以使用:
t = datetime.datetime(2012, 2, 23, 0, 0)
"{:%m/%d/%Y}".format(t)
输出:
'02/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
如果您正在寻找datetime到字符串转换的简单方法,可以省略该格式。您可以将datetime对象转换为str对象,然后使用数组切片。
In [1]: from datetime import datetime
In [2]: now = datetime.now()
In [3]: str(now)
Out[3]: '2019-04-26 18:03:50.941332'
In [5]: str(now)[:10]
Out[5]: '2019-04-26'
In [6]: str(now)[:19]
Out[6]: '2019-04-26 18:03:50'
但是注意下面的事情。如果其他解决方案会在变量为None时引发AttributeError,在这种情况下,您将收到一个'None'字符串。
In [9]: str(None)[:19]
Out[9]: 'None'