def _GetPatternsDistance(pattern_a, pattern_b):
  """Calculates the distance between two patterns.

  Args:
    pattern_a: a SimilarPattern or TimeSpan.
    pattern_b: a SimilarPattern or TimeSpan.
  Returns:
    Distance in seconds between the two patterns. If they are overlapped, the
      distance is 0.
  """
  end_a = pattern_a.start_time + pattern_a.duration
  end_b = pattern_b.start_time + pattern_b.duration

  b_falls_in_a = pattern_a.start_time <= end_b and end_b <= end_a
  a_falls_in_b = pattern_b.start_time <= end_a and end_a <= end_b

  if b_falls_in_a or a_falls_in_b:
    return 0
  elif pattern_a.start_time < pattern_b.start_time:
    return pattern_b.start_time - end_a
  else:
    return pattern_a.start_time - end_b