Python's method of calculating time lag

Source: Internet
Author: User
Tags datetime

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.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.