Change days to int without pandas in python

Question:

Is there any way to convert the resulting days into INT without pandas? Or use the number of days to do "for" loop?

from datetime import datetime, timedelta

d = datetime.today() - timedelta(days=10) 
date = datetime.today() - d

print(date)

Result:

10 days, 0:00:00

If I try for loop, it doesn’t work.

for days in range(date):
    print("■")

Error:

line 16, in <module>
    for i in range(date):
TypeError: 'datetime.timedelta' object cannot be interpreted as an integer

Newb, thank you.

Asked By: Sarian Morio

||

Answers:

You could try

"astype"

date = date.astype(int)
Answered By: 29belgrade29

When you subtract two datetime.datetime objects, the result is a datetime.timedelta. Check out the linked docs page for more information. From the docs:

Instance attributes (read-only):

Attribute Value
days Between -999999999 and 999999999 inclusive
seconds Between 0 and 86399 inclusive
microseconds Between 0 and 999999 inclusive

Accessing the .days attribute gives the number of days as an integer.

So your example should look something like this:

In [1]: from datetime import datetime, timedelta
   ...:
   ...: delta = timedelta(days=10)

In [2]: for days in range(delta.days):
   ...:     print(days)
   ...:
0
1
2
3
4
5
6
7
8
9
Answered By: Michael Delgado
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.