How Python Calculates the time difference

Source: Internet
Author: User
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.

  • 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.