Python time difference calculation method, python Time Difference Calculation
This article describes how to calculate the time difference in python. Share it with you for your reference. The specific analysis is as follows:
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 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), 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.
I hope this article will help you with Python programming.