1

Suppose I have a tuple A. It contains two nested tuples. The nested tuples are dates of the form DD,MM,YYYY.

A = ((DD,MM,YYYY), (DD,MM,YYYY))

Now, I want to find the number of days between the two dates. I've already tried fiddling with datetime module and it only helps when objects are integers and not tuples. My problem constraint is that I cannot change the structure in which dates are represented. I suppose I can use slicing but that would be way too much work. I'm pretty new at this and I hope someone can shed some light my way.

Mr.X
  • 59
  • 5

3 Answers3

2

You can use datetime.strptime to create a datetime object from the given string. Then you can subtract date1 and date2 which gives you a timedelta object and this timedelta object has a nice attribute days which gives you the number of days between two dates.

Use:

from datetime import datetime

date1 = datetime.strptime("-".join(A[0]), "%d-%m-%Y")
date2 = datetime.strptime("-".join(A[1]), "%d-%m-%Y")
diff_days = (date1 - date2).days

print(diff_days)

For example consider,

A = (("24","05","2020"), ("25","04","2020")) then the above code will print diff_days as 29.

Shubham Sharma
  • 68,127
  • 6
  • 24
  • 53
1

Code written on my smartphone. Basic idea convert with datetime and a f string to datetime object within a list comprehension. Build the timedelta and finally get the result in different formats

A=((3,4,2000), (4,4,2000))

from datetime import datetime

dt = [datetime.strptime(f'{a[0]}.{a[1]}.{a[2]}','%d.%m.%Y') for a in A]
td = dt[1] - dt[0]

# when you want a tuple w only days
difference_tuple = (td.days)

# days, hours, minutes
days, hours, minutes = td.days, td.seconds // 3600, td.seconds // 60 % 60
difference_tuple2 = (days, hours, minutes)
Björn
  • 1,610
  • 2
  • 17
  • 37
1

why is slicing too much work?

import datetime

# A = ((DD,MM,YYYY), (DD,MM,YYYY))

A = ((1,1,2020), (20,4,2020))

delta = (
    datetime.date(A[1][2],A[1][1],A[1][0])-
    datetime.date(A[0][2],A[0][1],A[0][0])
)

Phillyclause89
  • 674
  • 4
  • 12