简体   繁体   中英

TypeError: an integer is required (got type tuple) datetime Python

I am trying to get the days between two dates. Here is my code:

from datetime import date, timedelta
def days_diff(a, b):
    f = date(a)
    s = date(b)
    return abs(f-s)
print(days_diff((2014, 8, 27), (2014, 1, 1)))

But I get this error:

TypeError: an integer is required (got type tuple)

I wonder why? I imported the date and timedelta. Can anyone please help? Thanks in advance

You faced error because you passed a tuple to the date() , which takes values but not a tuple.
Try this:

def days_diff(a, b):
    f = date(*a)
    s = date(*b)
    print(f,s)
    return abs(f-s)

Now call it:

print(days_diff((2014, 8, 27), (2014, 1, 1)))

This will give you:

2014-08-27 2014-01-01
238 days, 0:00:00

The * takes out the value of the tuple passed (unpack the tuple).


To get the days alone, use .days :

return print(abs(f-s).days)

You need to pass 3 parameters to date() , not a tuple . You can unpack the tuples in your function with:

f = date(*a)
s = date(*b)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM