0

I am trying to calculate the number of days b/w two given days.The problem that I am facing is when the first day comes late as compared to the second day. Example-If the first day is Saturday and the second one is Monday so the number of days that exists b/w them should be 3 but my code fails to do this.

a="saturday monday 1 2" f=a.split(" ") l=["monday","tuesday","wednesday","thursday","friday","saturday","sunday"] g=abs(l.index(f[0])-l.index(f[1]))+1 print(g) 
4
  • Use modulus to wrap the negative index difference around. Commented May 17, 2019 at 10:27
  • Possible duplicate of How to compare two dates? Commented May 17, 2019 at 10:33
  • Days between Saturday and Monday will be 1 right, which is Sunday Commented May 17, 2019 at 10:48
  • I think there should be 2 days from Saturday to Monday, if from Saturday and Saturday there are zero Commented May 17, 2019 at 10:48

2 Answers 2

2

Subtract indexes for both days, and take a modulo 7. Putting this in a function, we have

def day_diff(a, b): l = ["monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday"] return (l.index(b) - l.index(a))%7 print(day_diff('saturday', 'monday')) #2 print(day_diff('monday', 'saturday')) #5 print(day_diff('monday', 'monday')) #0 print(day_diff('monday', 'sunday')) #6 
Sign up to request clarification or add additional context in comments.

Comments

1

This will handle your problem:

a="saturday monday 1 2" #a= "monday tuesday" f=a.split(" ") l=["monday","tuesday","wednesday","thursday","friday","saturday","sunday"] sym = (l.index(f[0])-l.index(f[1])) if sym <= 0: g=abs(sym)+1 else: new_sym = 7 - sym g=abs(new_sym)+1 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.