How to calculate difference between two dates in weeks in python

前端 未结 6 1525
花落未央
花落未央 2020-12-02 23:02

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,

6条回答
  •  没有蜡笔的小新
    2020-12-02 23:16

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

    from datetime import datetime, timedelta
    
    monday1 = (d1 - timedelta(days=d1.weekday()))
    monday2 = (d2 - timedelta(days=d2.weekday()))
    
    print 'Weeks:', (monday2 - monday1).days / 7
    

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

提交回复
热议问题