-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdate.py
38 lines (26 loc) · 1.1 KB
/
date.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
#!/usr/bin/python
import calendar
import datetime
DATE_FORMAT = "%m/%d/%Y"
# http://stackoverflow.com/questions/1060279/iterating-through-a-range-of-dates-in-python
def daterange(startDate, endDate):
for numDaysDelta in range(int ((endDate - startDate).days)):
yield startDate + datetime.timedelta(numDaysDelta)
# http://stackoverflow.com/questions/4130922/how-to-increment-datetime-month-in-python
def addMonthToDate(date, months=1):
month = date.month - 1 + months
year = date.year + (month / 12) # purposeful integer division
month = (month % 12) + 1
day = pinDayToMonth(year, month, date.day)
return datetime.date(year, month, day)
def pinDayToMonth(year, month, day):
return min(day, calendar.monthrange(year, month)[1])
def getPinnedDayOfNextMonth(year, month, day):
"""
Ignore the day in date and use the day passed in instead. This is useful if
you're doing math on the date, and the date's day may have already been pinned.
"""
year = year + (month / 12) # purposeful integer division
month = (month % 12) + 1
day = pinDayToMonth(year, month, day)
return datetime.date(year, month, day)