Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Change days to int without pandas in python

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading