This example describes how Python calculates the time difference. Share to everyone for your reference. The specific analysis is as follows:
1. Questions:
Given your two dates, how do you calculate between these two dates in a few days, weeks, months, years?
2. Solution:
The standard module datetime and third-party package dateutil (especially the Dateutil Rrule.count method) can help you solve this problem very quickly and easily.
From dateutil import rruleimport datetimedef 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), year (yearly). Here's a piece of code to test:
If _ _name_ _== ' _ _main_ _ ': starts = [Datetime.date (2005,, Datetime.date)] end = 2005 Te (2005, MB) for s in starts: Days = Rrule.rrule (rrule. DAILY, Dtstart=s, Until=end). Count () print "%d days shows as%d weeks" percent (days, weeks_between (s, end))
This will output the result:
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 a result of 0.5 weeks, so 8 days will be counted as two weeks.
Of course you don't have to define a size, just a return Rrule.rrule (Rrule). WEEKLY, Dtstart=start_date, Until=end_date). Count () to get the results.
Hopefully this article will help you with Python programming.