Last active
August 11, 2017 11:14
-
-
Save kevsersrca/fdb0072e8a897f666a2ab29045958639 to your computer and use it in GitHub Desktop.
first day and end day on month
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def firstOfMonth(day): | |
resultDate = day.replace(day=1) | |
if ((day - resultDate).days > 25): | |
resultDate = resultDate + relativedelta(months=1) | |
return resultDate | |
def lastOfMonth(any_day): | |
next_month = any_day.replace(day=28) + datetime.timedelta(days=4) # this will never fail | |
return next_month - datetime.timedelta(days=next_month.day) | |
def monthdelta(date, delta): | |
m, y = (date.month+delta) % 12, date.year + ((date.month)+delta-1) // 12 | |
if not m: m = 12 | |
d = min(date.day, [31, | |
29 if y%4==0 and not y%400==0 else 28,31,30,31,30,31,31,30,31,30,31][m-1]) | |
return date.replace(day=d,month=m, year=y) | |
print(firstOfMonth(datetime.date.today())) | |
print lastOfMonth(datetime.date(2017, 8, 11)) | |
print(monthdelta(datetime.date.today(), -1)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment