-->

搬运月蟒日期时间(Handling months in python datetimes)

2019-07-22 08:57发布

我有一个函数,得到该月的开始日期时间前提供:

def get_start_of_previous_month(dt):
    '''
    Return the datetime corresponding to the start of the month
    before the provided datetime.
    '''
    target_month = (dt.month - 1)
    if target_month == 0:
        target_month = 12
    year_delta = (dt.month - 2) / 12
    target_year = dt.year + year_delta

    midnight = datetime.time.min
    target_date = datetime.date(target_year, target_month, 1)
    start_of_target_month = datetime.datetime.combine(target_date, midnight)
    return start_of_target_month

然而,这似乎很令人费解。 任何人都可以提出一个更简单的方法? 我使用Python 2.4。

Answer 1:

使用timedelta(days=1) 月初的偏移量:

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)返回在当前月份的开始,一个新的日期后减去一天是要保证我们之前在本月结束。 然后,我们再拉同样的伎俩,以获得月的第一天。

演示(Python的2.4可以肯定):

>>> 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)


文章来源: Handling months in python datetimes