简体   繁体   English

类型错误:需要一个 integer(获取类型元组)日期时间 Python

[英]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.您遇到了错误,因为您将元组传递给date() ,它接受值但不接受元组。
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 :要单独获得这些日子,请使用.days

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

You need to pass 3 parameters to date() , not a tuple .您需要将 3 个参数传递给date() ,而不是tuple You can unpack the tuples in your function with:您可以使用以下命令解压缩 function 中的元组:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Python - 类型错误:需要一个 integer(获取类型 datetime.datetime) - Python - TypeError: an integer is required (got type datetime.datetime) TypeError:需要一个 integer(获取类型元组)<python><opencv><tesseract></tesseract></opencv></python> - TypeError: an integer is required (got type tuple) <python> <OpenCV> <tesseract> Python TypeError:需要一个整数(得到类型元组)-(OpenCV / Numpy) - Python TypeError: an integer is required (got type tuple) - (OpenCV / Numpy) 类型错误:需要一个 integer(获取类型元组)|| python 中的网站阻止代码 - TypeError: an integer is required (got type tuple) || website blocking code in python Python TypeError:整数是必需的(got类型列表) - Python TypeError: an integer is required (got type list) Python:类型错误:需要一个整数(得到类型 str) - Python: TypeError: an integer is required (got type str) TypeError:Python中需要一个整数(类型为str) - TypeError: an integer is required (got type str) in python Python: TypeError: an integer is required (got type module) - Python: TypeError: an integer is required (got type module) Python:TypeError 需要 integer(获取类型 str) - Python: TypeError an integer is required(got type str) Python 3,无法将日期时间戳转换为日期对象,TypeError:必需为整数(类型为str) - Python 3 , Unable to convert datetime stamp to datetime object, TypeError: an integer is required (got type str)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM