Advertisement
Guest User

Untitled

a guest
May 5th, 2016
80
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.51 KB | None | 0 0
  1. def time_difference(time_start, time_end):
  2. '''Calculate the difference between two times on the same date.
  3.  
  4. Args:
  5. time_start: the time to use as a starting point
  6. time_end: the time to use as an end point
  7.  
  8. Returns:
  9. the difference between time_start and time_end. For example:
  10.  
  11. >>> time_difference(1500, 1600)
  12. 60
  13.  
  14. >>> time_difference(1100, 1310)
  15. 130
  16.  
  17. Raises:
  18. TypeError: if time_start and time_end is not a string
  19. ValueError: if time_start and time_end is below 0 or above 2400
  20. '''
  21.  
  22. try:
  23. if not isinstance(time_start, str):
  24. raise TypeError('time_start has to be a string!')
  25. elif not isinstance(time_end, str):
  26. raise TypeError('time_end has to be a string!')
  27. elif int(time_start) > 2400 or int(time_end) < 0:
  28. raise ValueError('time_start nor time_end can be below 0 or above 2400!')
  29. elif int(time_start) > int(time_end):
  30. raise ValueError('time_start cannot be higher than time_end!')
  31. except (TypeError, ValueError):
  32. raise
  33.  
  34. # Convert time_start and time_end to necessary variables
  35. # for the calculation.
  36. hours_begin = time_start[0] + time_start[1]
  37. minutes_begin = time_start[2] + time_start[3]
  38. hours_end = time_end[0] + time_end[1]
  39. minutes_end = time_end[2] + time_end[3]
  40.  
  41. # Calculates the difference.
  42. minutes = ((int(hours_end) - int(hours_begin)) * 60 +
  43. int(minutes_end) - int(minutes_begin))
  44.  
  45. return(minutes)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement