Documentation

datetime.difference_relative

Return a dict describing the relative difference between dt1 and dt2 in seconds, minutes, hours, days, and years. Relative difference will not take into account hours or minutes lost or gained during timezone transitions. For example, when two datetimes occur on different sides of a transition, hours gained or lost will be ignored.

Arguments:

def datetime.difference_relative(
  dt1: <datetime> = None,
  dt2: <datetime> = None,
):

Returns <dict>:

{
  'years': <dec>,
  'months': <dec>,
  'weeks': <dec>,
  'days': <dec>,
  'hours': <dec>,
  'minutes': <dec>,
  'seconds': <dec>,
}

Example:

then = datetime.from_date_and_time(year=1990, month=3, day=21, hour=0, minute=0, second=0)
after_then = datetime.add(dt=then, days=16)
# diff == {
#   'years': 0,
#   'months': 0,
#   'weeks': 2,
#   'days': 2,
#   'hours': 0, # No accounting for DST change here
#   'minutes': 0,
#   'seconds': 0,
# }
diff = datetime.difference_relative(dt1=after_then, dt2=then)

# diff_hours == 383
# By contrast, the difference in hours is 383, accounting for DST.
diff_hours = datetime.difference(dt1=after_then, dt2=then, as_hours=True)

# diff_days == 16
# Nonetheless, the number of days returned here is still rounded to 16.
diff_days = datetime.difference(dt1=after_then, dt2=then, as_days=True)