python - 在 python 日期时间中处理月份

标签 python datetime python-2.4

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

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。

最佳答案

使用这个月开始的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)

关于python - 在 python 日期时间中处理月份,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15547217/

相关文章:

python - 可以通过自定义 SQLObject Select 调用获取生成器吗?

python - groupby 后为唯一多索引值的组合填充零值

python - pypyodbc - 重用数据库连接

python - 如何在 Pexpect spawn 中设置环境变量而不会出现异常

python - 反正弦的变体

sql-server - 如何在 SQL SERVER 中格式化日期时间

python + 运行带变量的系统命令

python - 我的代码的第 102 行总是出错

asp.net-mvc-3 - DateTime 属性的 MVC3 默认值

python2.4.3 : format bug?