Skip to content

Instantly share code, notes, and snippets.

@jColeChanged
Created June 22, 2012 00:21
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 jColeChanged/2969454 to your computer and use it in GitHub Desktop.
Save jColeChanged/2969454 to your computer and use it in GitHub Desktop.
These are a few helper functions I ended up wanting while working with months while doing freelance work. I'm putting them up here since, though simple, they ended up being useful enough that if I ever work with dates again I'll probably end up using them
import datetime
from dateutil.relativedelta import relativedelta
def relative_month(d, months):
"""Accepts a datetime or date object and returns another datetime object.
The returned datetime is the start of the datetime n months away. This does
not have side effects.
Args:
d - a date or datetime object
months - an integer representing the number of months to adjust d
Return:
an adjusted datetime
"""
return start_of_month(d + relativedelta(months=months))
def start_of_month(d):
"""Accepts a datetime or date object. Returns a datetime object of the same
year and month. Does not have side effects.
Args:
d - a date or datetime object
Returns:
a datetime object representing the start of the month in d
"""
return datetime.datetime(d.year, d.month, 1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment