Search code examples
pythonpython-3.xdatetimepython-datetimeweekday

Difference between two timestamps with different weekdays?


I've the following dates:

Tue 19:00-20:00
Wed 04:25-15:14

How can i get the difference between Tue 20:00 and Wed 04:25?

I've tried to transform it in datetime objects but since i don't have the day of the month or a year both objects will get the same date:

d1 = datetime.strptime("Tue 20:00", "%a %H:%M")
d2 = datetime.strptime("Wed 04:25", "%a %H:%M")
  • d1 is: datetime.datetime(1900, 1, 1, 20, 0)
  • d2 is: datetime.datetime(1900, 1, 1, 4, 25)

The difference in minutes should be 505 but in this case will be -935.0 because they have the same date, and so they differ by almost 16 hours and not about 8 and a half:

diff = (d2 - d1).total_seconds() / 60  # -935.0

Solution

  • datetime.strptime() can't do anything else, because the day of the week is not enough to form a date. You'd need a week number and a year for a week-day to make any sense. If you need to get the relative difference between two dates that are assumed to be in the same week, then any week number and year would do, e.g.:

    arbitrary_iso_week = "2020-25 "
    
    d1 = datetime.strptime(arbitrary_iso_week + "Tue 20:00", "%G-%V %a %H:%M")
    d2 = datetime.strptime(arbitrary_iso_week + "Wed 04:25", "%G-%V %a %H:%M")
    

    This makes use of the %G and %V formatters for ISO 8601 week numbers.

    This produces datetime objects with a more meaningful date releationship:

    >>> arbitrary_iso_week = "2020-25 "
    >>> d1 = datetime.strptime(arbitrary_iso_week + "Tue 20:00", "%G-%V %a %H:%M")
    >>> d2 = datetime.strptime(arbitrary_iso_week + "Wed 04:25", "%G-%V %a %H:%M")
    >>> d1
    datetime.datetime(2020, 6, 16, 20, 0)
    >>> d2
    datetime.datetime(2020, 6, 17, 4, 25)
    >>> (d2 - d1).total_seconds() / 60
    505.0
    

    The actual dates don't matter here, just their difference in days. d1 is now earlier, not later, than d2.

    You may have to take into account that week days are circular, in that you could have an earlier date on, say, Friday, and a later date on Monday. If you can assume that the first value must be earlier than the second, then the solution is simple. Just subtract 7 days from d1 if it is later than d2:

    # if the first date must come before the second, then it must be one week earlier.
    if d1 > d2:
        d1 -= timedelta(days=7)