Python time difference calculation method, python Time Difference Calculation

Source: Internet
Author: User

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.

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.