Created
June 22, 2012 00:21
-
-
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
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
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