import datetime from calendar import monthrange from django.utils import timezone def start_of_month(a_day): """ Returns first of the month of a given datetime object""" return a_day.replace(day=1,hour=0,minute=0,second=0, microsecond=0) def end_of_month(a_day): """ Returns first of the month of a given datetime object""" _, last_day = monthrange(a_day.year, a_day.month) return a_day.replace(day=last_day,hour=23,minute=59,second=59, microsecond=0) def start_of_this_month(): """ Returns first of this month""" a_day = timezone.now() return a_day.replace(day=1,hour=0,minute=0,second=0, microsecond=0) def end_of_this_month(): """ Returns first of this month""" a_day = timezone.now() _, last_day = monthrange(a_day.year, a_day.month) return a_day.replace(day=last_day,hour=23,minute=59,second=59, microsecond=0) def end_before(a_date): """ Return suitable datetimefield for ending just before a_date """ return a_date - datetime.timedelta(seconds=1) def start_after(a_date): """ Return suitable datetimefield for starting just after a_date """ return a_date + datetime.timedelta(seconds=1)