Advertisement
Guest User

Untitled

a guest
Sep 19th, 2014
256
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.40 KB | None | 0 0
  1. def last_n_months(n=12, ending=None):
  2. """Return a list of tuples of the first/last day of the month
  3. for the last N months
  4. """
  5. from datetime import date
  6. from dateutil.rrule import rrule, MONTHLY
  7. from dateutil.relativedelta import relativedelta
  8.  
  9. if not ending:
  10. ending = date.today()
  11.  
  12. # set the ending date to the last day of the month
  13. ending = ending + relativedelta(months=+1, days=-ending.day)
  14.  
  15. # starting is the first day of the month N months ago
  16. starting = ending - relativedelta(months=n, day=1)
  17.  
  18. months = list(rrule(MONTHLY, bymonthday=(1, -1), dtstart=starting,
  19. until=ending))
  20.  
  21. # we return pairs of dates like this: (1st day of month, last day of month)
  22. months = zip(months[::2], months[1::2])
  23.  
  24. return months
  25.  
  26. >>> from datetime import date, timedelta
  27.  
  28. # get last two months as a degenerate example
  29. >>> l2n = last_n_months(2, ending=date(2012, 01, 01))
  30. >>> map(lambda x: [x[0].year, x[0].month, x[0].day], l2n)
  31. [[2011, 11, 1], [2011, 12, 1], [2012, 1, 1]]
  32. >>> map(lambda x: [x[1].year, x[1].month, x[1].day], l2n)
  33. [[2011, 11, 30], [2011, 12, 31], [2012, 1, 31]]
  34.  
  35. >>> l24n = last_n_months(24, ending=date(2012,03,16))
  36. >>> len(l24n) # inclusive of current month
  37. 25
  38.  
  39. # every tuple starts with the first day of the month
  40. >>> all(x[0].day == 1 for x in l24n)
  41. True
  42.  
  43. # every tuple ends with the last day of the month
  44. >>> all((x[1] +timedelta(days=1)).month != x[1].month for x in l24n)
  45. True
  46.  
  47. # every tuple is the same month
  48. >>> all(x[0].month == x[1].month for x in l24n)
  49. True
  50.  
  51. def last_n_months(n=12, ending=None):
  52. """Return a list of tuples of the first/last day of the month
  53. for the last N months
  54. """
  55. from datetime import date
  56. from dateutil.rrule import rrule, MONTHLY
  57. from dateutil.relativedelta import relativedelta
  58.  
  59. if not ending:
  60.  
  61. ending = date.today()
  62.  
  63. # set the ending date to the last day of the month
  64. ending = ending + relativedelta(months=+1, days=-ending.day)
  65.  
  66. # starting is the first day of the month N months ago
  67. starting = ending - relativedelta(months=n, day=1)
  68.  
  69. months = list(rrule(MONTHLY, bymonthday=(1, -1), dtstart=starting,
  70. until=ending))
  71.  
  72. # we return pairs of dates like this: (1st day of month, last day of month)
  73. months = zip(months[::2], months[1::2])
  74.  
  75. return months
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement