The example in this article describes how Python calculates time lag. Share to everyone for your reference. The specific analysis is as follows:
1, Questions:
Given your two date, how do you calculate the interval between these two dates, weeks, months, years?
2, the solution:
Standard module datetime and third party package dateutil (especially the Dateutil Rrule.count method) can help you solve this problem very quickly and easily.
?
1 2 3 4 5 |
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 scale calculations based on the date (daily), Week (WEEKLY), year (yearly). Here's a piece of code to test:
?
1 2 3 4 5 6 |
If _ _name_ _== ' _ _main_ _ ': Starts = [Datetime.date (+), datetime.date (+)] End = Datetime.date (2005, (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) |
This result will be output:
7 days shows as 1 weeks
8 days shows as 2 weeks
The Rrule calculation is calculated as an integer, and it does not return results of 0.5 weeks, so 8 days will be counted as two weeks.
Of course you can not define a size, directly a return Rrule.rrule (Rrule. WEEKLY, Dtstart=start_date, Until=end_date). Count () to get the result.
I hope this article will help you with your Python programming.