Created
July 27, 2011 11:01
-
-
Save waynemoore/1109153 to your computer and use it in GitHub Desktop.
Get first and last day of a particular month using python-dateutil.
This file contains 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 | |
# requires python-dateutil (http://labix.org/python-dateutil) | |
from dateutil.relativedelta import relativedelta | |
def get_month_day_range(date): | |
""" | |
For a date 'date' returns the start and end date for the month of 'date'. | |
Month with 31 days: | |
>>> date = datetime.date(2011, 7, 27) | |
>>> get_month_day_range(date) | |
(datetime.date(2011, 7, 1), datetime.date(2011, 7, 31)) | |
Month with 28 days: | |
>>> date = datetime.date(2011, 2, 15) | |
>>> get_month_day_range(date) | |
(datetime.date(2011, 2, 1), datetime.date(2011, 2, 28)) | |
""" | |
last_day = date + relativedelta(day=1, months=+1, days=-1) | |
first_day = date + relativedelta(day=1) | |
return first_day, last_day | |
if __name__ == "__main__": | |
import doctest | |
doctest.testmod() |
Elegant implementation @ fletom
Very simple yet effective @fletom
An alternative version with no requirements outside of Python's standard library:
import datetime import calendar def get_month_day_range(date): """ For a date 'date' returns the start and end date for the month of 'date'. Month with 31 days: >>> date = datetime.date(2011, 7, 27) >>> get_month_day_range(date) (datetime.date(2011, 7, 1), datetime.date(2011, 7, 31)) Month with 28 days: >>> date = datetime.date(2011, 2, 15) >>> get_month_day_range(date) (datetime.date(2011, 2, 1), datetime.date(2011, 2, 28)) """ first_day = date.replace(day = 1) last_day = date.replace(day = calendar.monthrange(date.year, date.month)[1]) return first_day, last_day if __name__ == "__main__": import doctest doctest.testmod()
nice, it work for me, simples and elegant
Bravo fletom!
@fletom ,
May I know how to run this?
I'm new in python.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
An alternative version with no requirements outside of Python's standard library: