Guest User

Untitled

a guest
Jul 17th, 2018
67
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.68 KB | None | 0 0
  1. import sys
  2. import unittest
  3.  
  4. class InvalidDateException(Exception):pass
  5.  
  6. def is_leap(year):
  7. if year % 400 == 0:
  8. return True
  9. elif year % 100 == 0:
  10. return False
  11. elif year % 4 == 0:
  12. return True
  13. else:
  14. return False
  15.  
  16. parse_date = lambda x: map(int, x.split('-'))
  17.  
  18. def day_of_year(date):
  19. day, month, year = parse_date(date)
  20.  
  21. if month < 1 or month > 12:
  22. raise InvalidDateException("invalid month - %d" % month)
  23.  
  24. days_in_month = [0, 31, 28, 31, 30, 31, 30, 31,
  25. 31, 30, 31, 30, 31]
  26. if month > 2 and is_leap(year):
  27. days_in_month[2] = 29
  28. else:
  29. days_in_month[2] = 28
  30.  
  31. if day > days_in_month[month]:
  32. raise InvalidDateException("month %d doesn't have %d days" % (month,
  33. day))
  34.  
  35. for i in range(1,month):
  36. day += days_in_month[i]
  37.  
  38. return day
  39.  
  40. def age(start_date_str, end_date_str):
  41. """ start_date < end_date """
  42. start_date, end_date = map(parse_date, (start_date_str, end_date_str))
  43. print start_date, end_date
  44. days = (365 if not is_leap(start_date[2]) else 366) - \
  45. day_of_year(start_date_str)
  46. print "Start - %d: %d" % (start_date[2], days)
  47.  
  48. for year in range(start_date[2] + 1 , end_date[2]):
  49. if is_leap(year): days += 366
  50. else: days += 365
  51. print "Loop - %d: %d" % (year, days)
  52.  
  53. if end_date[2] > start_date[2]:
  54. days += day_of_year(end_date_str)
  55. else:
  56. days = day_of_year(end_date_str) - days
  57. print "End - %d" % days
  58. return days
  59.  
  60.  
  61. if __name__ == '__main__':
  62. args = len(sys.argv)
  63. if args > 2:
  64. print age(sys.argv[1], sys.argv[2])
  65. elif args > 1:
  66. print day_of_year(sys.argv[1])
Add Comment
Please, Sign In to add comment