Recipe 3.3. Calculating Time Periods in a Date Range
1. Problem:
How can we calculate the interval of days, weeks, months, and years between two dates given to you?
2. solution:
The standard module datetime and third-party package dateutil (especially the rrule. count Method of dateutil) can help you solve this problem very easily and quickly.
From dateutil import rrule
Import datetime
Def weeks_between (start_date, end_date ):
Weeks = rrule. rrule (rrule. WEEKLY, dtstart = start_date, until = end_date)
Return weeks. count ()
The rrule method allows you to set the Scale Calculation Based on the date (DAILY), Week (WEEKLY), and year (YEARLY. Use a piece of code to test it:
If _ name _ = '_ main __':
Starts = [datetime. date (2005, 01, 04), datetime. date (2005, 01, 03)]
End = datetime. date (2005, 01, 10)
For s in starts:
Days = rrule. rrule (rrule. DAILY, dtstart = s, until = end). count ()
Print "% d days shows as % d weeks" % (days, weeks_between (s, end ))
The output result is as follows:
7 days shows as 1 weeks
8 days shows as 2 weeks
Rrule is calculated as an integer. It does not return results such as 0.5 weeks. Therefore, 8 days are counted as two weeks.
Of course, you do not need to define a dimension. You can directly return rrule. rrule (rrule. WEEKLY, dtstart = start_date, until = end_date). count () to get the result.
03.03.2009 by vivilisa