Handling months in python datetimes

前端 未结 1 1925
死守一世寂寞
死守一世寂寞 2021-01-14 07:45

I have a function which gets the start of the month before the datetime provided:

def get_start_of_previous_month(dt):
    \'\'\'
    Return the datetime cor         


        
相关标签:
1条回答
  • 2021-01-14 08:16

    Use a timedelta(days=1) offset of the beginning of this month:

    import datetime
    
    def get_start_of_previous_month(dt):
        '''
        Return the datetime corresponding to the start of the month
        before the provided datetime.
        '''
        previous = dt.date().replace(day=1) - datetime.timedelta(days=1)
        return datetime.datetime.combine(previous.replace(day=1), datetime.time.min)
    

    .replace(day=1) returns a new date that is at the start of the current month, after which subtracting a day is going to guarantee that we end up in the month before. Then we pull the same trick again to get the first day of that month.

    Demo (on Python 2.4 to be sure):

    >>> get_start_of_previous_month(datetime.datetime.now())
    datetime.datetime(2013, 2, 1, 0, 0)
    >>> get_start_of_previous_month(datetime.datetime(2013, 1, 21, 12, 23))
    datetime.datetime(2012, 12, 1, 0, 0)
    
    0 讨论(0)
提交回复
热议问题