将日期时间更改为字符串

2024-09-24 22:22:08 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图找到两个日期之间的天数,并将其输出为字符串。你知道吗

这是我的东西

currentDate = datetime.datetime.now()
newDate = currentDate + datetime.timedelta(days=3)
dateDifference = newDate - currentDate
print(dateDifference)

我试过了

print(dateDifference.strftime('%d'))

但这行不通。你知道吗

我只想把数字“3”说成一个字符串。你知道吗

谢谢。你知道吗


Tags: 字符串datetime数字daysnowtimedeltaprint天数
3条回答
from datetime import datetime, timedelta

currentDate = datetime.now()
newDate = currentDate + timedelta(days=3)
dateDifference = str(newDate - currentDate)
print(type(dateDifference))
print(dateDifference)

输出

<class 'str'>
3 days, 0:00:00
>>> 

为什么不:

>>> print(dateDifference.days)
3

或者如果你想要一个字符串,你可以做下面的代码,按照@BenT所采取的解决方案使用str,这是首选的(你应该使用这个),我会给出一个字符串格式的解决方案:

>>> print('%s' % dateDifference.days)
3
>>> type('%s' % dateDifference.days)
<class 'str'>

如果你想把日差作为一个字符串,你可以这样做

print(str(dateDifference.days))

相关问题 更多 >