将日期时间转换为字符串

3
我会尽力完成翻译工作。以下是您需要翻译的内容:

我想找出两个日期之间的天数,并将其输出为字符串。

这是我现在有的:

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

我尝试过

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

但是这样不起作用。

我希望输出结果只显示数字"3",以字符串形式呈现。

谢谢。

3个回答

2
如果你想将日期差作为字符串输出,可以这样做:
最初的回答:
如果您希望将日期差作为字符串输出,您可以执行以下操作:
print(str(dateDifference.days))

即使在Python 3中也没有string函数。 - user2357112
str,不好意思,我把2.7和3.x搞反了。 - BenT

1
为什么不呢:
>>> print(dateDifference.days)
3

或者,如果你想要一个字符串,你可以按照@BenT使用str的解决方案来执行下面的代码(建议使用该方法),我将提供一个使用字符串格式化的解决方案:

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

这会返回一个 int 值而不是作者想要的字符串。 - BenT
@BenT:如果你要打印它,就不需要手动调用 strprint 会为你做这个。 - user2357112
是的,但我假设打印该值不是海报使用它的最终产品。 - BenT
@user2357112 我同意。 - U13-Forward

0
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
>>> 

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接