[英]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.