How to calculate difference between two dates in weeks in python

前端 未结 6 1515
花落未央
花落未央 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:10

    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.

提交回复
热议问题