在python datetimes处理几个月 [英] Handling months in python datetimes

查看:234
本文介绍了在python datetimes处理几个月的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个函数可以在提供的datetime之前获得一个月的开始:

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

However, it seems very convoluted. Can anyone suggest a simpler way? I am using python 2.4.

推荐答案

使用 timedelta(days = 1)这个月份开始的偏移量:

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)返回在当月开始的新日期,之后减去一天将保证我们在上个月结束。然后,我们再次采取相同的技巧,以获得 月份的第一天。

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

演示(在Python 2.4中可以肯定):

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)

这篇关于在python datetimes处理几个月的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆