如何在python中以周为单位计算两个日期之间的差异

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14191832/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 10:43:25  来源:igfitidea点击:

How to calculate difference between two dates in weeks in python

pythondatetime

提问by recluze

I'm trying to calculate the difference between two dates in "weeks of year". I can get the datetime object and get the days etc but not week numbers. I can't, of course, subtract dates because weekends can't be ensured with that.

我正在尝试计算“一年中的几周”中两个日期之间的差异。我可以获取日期时间对象并获取天数等,但不能获取周数。当然,我不能减去日期,因为不能保证周末。

I tried getting the week number using d1.isocalendar()[1]and subtracting d2.isocalendar()[1]but the issue is that isocalendar()[1]returns December 31, 2012as week 1 (which supposedly is correct) but that means my logic cannot span over this date.

我尝试使用d1.isocalendar()[1]和减去来获取周数,d2.isocalendar()[1]但问题是isocalendar()[1]返回December 31, 2012第 1 周(这应该是正确的),但这意味着我的逻辑不能跨越这个日期。

For reference, here's my complete code:

作为参考,这是我的完整代码:

def week_no(self):
    ents = self.course.courselogentry_set.all().order_by('lecture_date')
    l_no = 1
    for e in ents:
        if l_no == 1: 
             starting_week_of_year = e.lecture_date.isocalendar()[1] # get week of year
             initial_year = e.lecture_date.year   
        if e == self: 
            this_year = e.lecture_date.year
            offset_week = (this_year - initial_year) * 52
            w_no = e.lecture_date.isocalendar()[1] - starting_week_of_year + 1 + offset_week
            break 
        l_no += 1
    return w_no  

With this code, the lecture on Dec 31, 2012 ends up being -35.

使用此代码,2012 年 12 月 31 日的讲座结果为 -35。

采纳答案by eumiro

How about calculating the difference in weeks between the Mondayswithin weeks of respective dates? In the following code, monday1is the Monday on or before d1(the same week):

如何计算各个日期数周内的星期一之间的周数差异?在下面的代码中,monday1是星期一或之前d1(同一周):

from datetime import datetime, timedelta

monday1 = (d1 - timedelta(days=d1.weekday()))
monday2 = (d2 - timedelta(days=d2.weekday()))

print 'Weeks:', (monday2 - monday1).days / 7

Returns 0if both dates fall withing one week, 1if on two consecutive weeks, etc.

返回0,如果这两个日期不在withing一周1如果连续两周,等等。

回答by Thomas Vander Stichele

You're a bit vague on what 'difference in weeks' means exactly. Is 6 days difference one week or zero ? Is eight days difference one week or two ?

您对“周差异”的确切含义有些含糊。6 天的差异是一周还是零?八天是一星期还是两个星期?

In any case, why can't you simply find the difference in another unit (seconds or days) and divide by the appropriate amount, with your prefered rounding for weeks?

在任何情况下,您为什么不能简单地找到另一个单位(秒或天)中的差异并除以适当的数量,并使用您喜欢的周数四舍五入?

回答by Rashmi Nagaraja

You may want to refer the Python CookBook (2005 edition) Recipe 3.3. The following code snippet is from the cookbook, does what you require.

您可能需要参考 Python CookBook(2005 版)Recipe 3.3。以下代码片段来自食谱,可满足您的要求。

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

回答by Neil

To determine how many weeks are spanned by two dates. eg From 3rd Oct to 13th Oct

确定两个日期跨越多少周。例如从 10 月 3 日到 10 月 13 日

    October 2015
Mo     5 12 19 26
Tu     6 13 20 27
We     7 14 21 28
Th  1  8 15 22 29
Fr  2  9 16 23 30
Sa  3 10 17 24 31
Su  4 11 18 25

Code:

代码:

    import math, datetime

    start_date = datetime.date(2015, 10, 3)
    start_date_monday = (start_date - datetime.timedelta(days=start_date.weekday()))
    end_date = datetime.date(2015, 10, 13)
    num_of_weeks = math.ceil((end_date - start_date_monday).days / 7.0)

Equals 3 weeks.

相当于 3 周。

回答by sbilkoloft

The solution above has a bug (I can't add a comment due to low reputation). It doesn't account for hour differences.

上面的解决方案有一个错误(由于声誉低,我无法添加评论)。它不考虑小时差异。

# This code has a bug.
monday1 = (d1 - timedelta(days=d1.weekday()))
monday2 = (d2 - timedelta(days=d2.weekday()))

Counter example of 2 dates more than a week apart:

两个日期相隔一周以上的反例:

Timestamp1: 1490208193270795 (22 Mar 2017 18:43:13 GMT)
Monday1: 20 Mar 2017 18:43:13 GMT

Timestamp2: 1489528488744290 (14 Mar 2017 21:54:48 GMT)
Monday2: 13 Mar 2017 21:54:48 GMT

Using that code it returns 0 as week diff when it should be 1. Need to zero out the hours/minutes/seconds as well.

使用该代码,当它应该是 1 时,它返回 0 作为周差异。还需要将小时/分钟/秒归零。

回答by Transformer

This is a very simple solution with less coding everyone would understand.

这是一个非常简单的解决方案,每个人都能理解的编码更少。

from datetime import date

d1 = date(year, month, day)
d2 = date(year, month, day)
result = (d1-d2).days//7