【问题标题】:Handling months in python datetimes在 python 日期时间中处理月份
【发布时间】:2013-03-21 12:13:14
【问题描述】:

我有一个函数可以在提供的日期时间之前获取月初:

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。

【问题讨论】:

    标签: python datetime python-2.4


    【解决方案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)
    

    【讨论】:

      猜你喜欢
      • 2015-03-27
      • 1970-01-01
      • 1970-01-01
      • 2018-10-15
      • 2012-04-30
      • 1970-01-01
      • 2013-09-23
      • 2019-01-07
      • 1970-01-01
      相关资源
      最近更新 更多