Home > Backend Development > Python Tutorial > python计算时间差的方法

python计算时间差的方法

WBOY
Release: 2016-06-10 15:12:08
Original
1705 people have browsed it

本文实例讲述了python计算时间差的方法。分享给大家供大家参考。具体分析如下:

1、问题:

给定你两个日期,如何计算这两个日期之间间隔几天,几个星期,几个月,几年?

2、解决方法:

标准模块datetime和第三方包dateutil(特别是dateutil的rrule.count方法)能非常简单迅速的帮你解决这个问题。

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( )

Copy after login

rrule方法允许你根据日期(DAILY),星期(WEEKLY),年(YEARLY)来设置尺度计算。下面用一段代码来测试一下:

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))

Copy after login

将输出这样的结果:

7 days shows as 1 weeks
8 days shows as 2 weeks

Rrule计算是以整数计算的,它不会返回0.5星期之类的结果,所以8天会被算为两个星期。

当然你可以不必定义一个尺寸,直接一句return rrule.rrule(rrule.WEEKLY, dtstart=start_date, until=end_date).count( )就可以得到结果。

希望本文所述对大家的Python程序设计有所帮助。

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template