Skip to content

Instantly share code, notes, and snippets.

@openrijal
Last active October 3, 2016 07:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save openrijal/c0f9ee53b7ec54b28b5e2ce2f9f54a1a to your computer and use it in GitHub Desktop.
Save openrijal/c0f9ee53b7ec54b28b5e2ce2f9f54a1a to your computer and use it in GitHub Desktop.
return first and last day of a month (in datetime)
from datetime import datetime, timedelta, date
def get_first_day(dt, d_years=0, d_months=0):
# d_years, d_months are "deltas" to apply to dt
y, m = dt.year + d_years, dt.month + d_months
a, m = divmod(m - 1, 12)
dt = date(y + a, m + 1, 1)
return datetime(dt.year, dt.month, dt.day, 0, 0, 0)
def get_last_day(dt):
dt = get_first_day(dt, 0, 1) + timedelta(-1)
return datetime(dt.year, dt.month, dt.day, 23, 59, 59)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment