Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save jceresearch/808d325d372e66a7e90a3813896d090b to your computer and use it in GitHub Desktop.
Save jceresearch/808d325d372e66a7e90a3813896d090b to your computer and use it in GitHub Desktop.
calculate beginning and end of the month given a date or datetime
from datetime import datetime, timedelta, date
def start_and_end_of_month(d,return_datetime=True):
if return_datetime:
if isinstance(d,date):
d=datetime(d.year,d.month,d.day)
start = d.replace(day=1)
next_month=d.replace(day=28)+timedelta(days=4)
end = next_month - timedelta(days=1)+timedelta(hours=23,minutes=59,seconds=59)
else:
start = d.replace(day=1)
next_month=d.replace(day=28)+timedelta(days=4)
end = next_month-timedelta(days=next_month.day)
return start, end
start_and_end_of_month(date.today())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment