Change a datetime to string

Viewed 67

I'm trying to find the number of days between two dates and output it as a string.

Here is what I have

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

I've tried

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

But this doesn't work.

I want the out to say only the number "3" as a string.

Thanks.

3 Answers

If you want the day difference as a string you can do

print(str(dateDifference.days))

Why not:

>>> print(dateDifference.days)
3

Or if you want a string, you can do the below code, as per @BenT took the solution using str, which is preferred (you should use that), I would give a solution with string formatting:

>>> print('%s' % dateDifference.days)
3
>>> type('%s' % dateDifference.days)
<class 'str'>
from datetime import datetime, timedelta

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

OUTPUT

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