Python:两个datetimes在几个月的差异 [英] Python: Difference of 2 datetimes in months

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

问题描述


可能重复:

找到两个日期之间的月份的最佳方式(在python中)

我想知道这个差异的确切月份数:

I would like to know how I can have the exact number of months for this difference:

date1 = datetime.strptime(str('2011-08-15 12:00:00'), '%Y-%m-%d %H:%M:%S')
date2 = datetime.strptime(str('2012-02-15'), '%Y-%m-%d')

date2-date1结果

date2-date1 results in

datetime.timedelta(183, 43200)

我想知道确切的月数,在这种情况下应该返回 5 而不是6(因为小时)

I would like to know the exact number of months, in this case it should return 5 and not 6 (because of the hour)

推荐答案

使用日历找出每个月有多少天,你可以简单地算几个月。

Using calendar module to find out how many days each month has, you can simply count the months.

from calendar import monthrange
from datetime import datetime, timedelta

def monthdelta(d1, d2):
    delta = 0
    while True:
        mdays = monthrange(d1.year, d1.month)[1]
        d1 += timedelta(days=mdays)
        if d1 <= d2:
            delta += 1
        else:
            break
    return delta

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

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