简体   繁体   中英

I don't know how to write the format for A tuple in the function in order to put any date I want as a tuple. Thank you in advance

def days_diff(a, b):
    A = tuple((), ()) 
    a = datetime.date(A[1][0],A[1][1],A[1][2])
    b = datetime.date(A[0][0],A[0][1],A[0][2])
        
    return abs (a-b).days
    
print(days_diff((1982, 4, 19), (1982, 4, 22)))  
# Expected output: 3 days

I want to have this output where you can put any dates as a tuple of integers. Currently I have this error: TypeError: tuple expected at most 1 arguments, got 2 .

Try this code:

import datetime
def days_diff(a, b):
    A = tuple(a+b)
    a = datetime.date(A[0],A[1],A[2]) # main change
    b = datetime.date(A[3],A[4],A[5]) # main change
    
    return abs (a-b).days

print(days_diff((1982, 4, 19), (1982, 4, 22)))  #3 days

First you need to merge the tuples a and b to A and then simply use tuple indexing to get the desired value.

The user will pass 2 tuples, so first we convert each tuple to date datetime.date(*a) , datetime.date(*b) . Now we get difference by subtracting one from other, and take absolute value np.abs(_ - _) which is our output. Note: datetime.date(*a) is equal to datetime.date(a[0], a[1], a[2])

import datetime

def days_diff(a, b):
    return str(np.abs(datetime.date(*a) - datetime.date(*b)))

print(days_diff((1982, 4, 19), (1982, 4, 22)))
# 3 days, 0:00:00

print(days_diff((1982, 4, 19), (1983, 4, 22)))
# 368 days, 0:00:00

print(days_diff((1980, 9, 19), (1982, 4, 22)))
# 580 days, 0:00:00

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