How to find the number of weeks between two dates in Python?
In this tutorial, we will learn how to find the number of weeks between two dates in Python. In Python, we have an inbuilt module called datetime. By using this datetime module, we can solve various datetime related problems. In datetime module, we have date function. By using this function, we can take two different dates. After that, we can easily subtract these two date types. After subtraction of these two date types, we will get the difference between these two dates in days. We will take the absolute value of this by using the abs() function to prevent the negative value. After this, we have to simply divide this value by 7 to get the difference between these two dates in number of weeks. Here we will use ‘//’ (floor division) operator to ignore the float value after division.
Find the number of weeks between two dates in Python
Let’s see an example of how we can do this easily :
#import date function from datetime module from datetime import date #provide the 1st date in YYYY,MM,DD format date1 = date(1999,12,23) #provide the 1st date in YYYY,MM,DD format date2 = date(2001,5,11) #getting the result, abs = absolute value #(date1-date2).days gives an integer number of dates days = abs(date1-date2).days #caculating and printing the weeks, // = floor division operator print (days//7)
Note: Always provide date in ‘YYYY,MM,DD’ format. Suppose we want to provide date as 23rd Dec, 1999. Then we’ll type ‘1999, 12, 23’. And remind one more thing don’t put 0 value before any integer inside the function otherwise you may get an error. Suppose, you want to provide date as 1st Jan, 2020. Then just type ‘2000,1,1’. Don’t put like ‘2020-01-01’.
I hope now you’re familiar with the concept of how we can calculate the number of weeks between two dates.