![](/img/trans.png)
[英]Python - TypeError: an integer is required (got type datetime.datetime)
[英]TypeError: an integer is required (got type tuple) datetime Python
我正在嘗試獲取兩個日期之間的天數。 這是我的代碼:
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)))
但我得到這個錯誤:
TypeError: an integer is required (got type tuple)
我想知道為什么? 我導入了日期和時間增量。 有人可以幫忙嗎? 提前致謝
您遇到了錯誤,因為您將元組傳遞給date()
,它接受值但不接受元組。
嘗試這個:
def days_diff(a, b):
f = date(*a)
s = date(*b)
print(f,s)
return abs(f-s)
現在調用它:
print(days_diff((2014, 8, 27), (2014, 1, 1)))
這會給你:
2014-08-27 2014-01-01
238 days, 0:00:00
*
取出傳遞的元組的值(解包元組)。
要單獨獲得這些日子,請使用.days
:
return print(abs(f-s).days)
您需要將 3 個參數傳遞給date()
,而不是tuple
。 您可以使用以下命令解壓縮 function 中的元組:
f = date(*a)
s = date(*b)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.