【问题标题】:Calculate with date, without import dateutil使用日期计算,无需导入 dateutil
【发布时间】:2016-07-29 12:11:04
【问题描述】:
from datetime import datetime
from dateutil import relativedelta
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')
r = relativedelta.relativedelta(date2, date1)
r.months

上面的代码对我有用,但我不想导入 dateutil。有没有人给我一个没有循环的例子?

我想从彼此中减去两个日期,并且我想知道整个月份中两个日期之间的月差。

【问题讨论】:

标签: python python-2.7


【解决方案1】:

看来这篇文章有帮助:How do I find the time difference between two datetime objects in python?

只需对两个 datetime obj 做减法,就可以在 diff 中得到你想要的细节。

【讨论】:

    【解决方案2】:

    有趣的是,您的代码输出到:5,这意味着,正如 cmets 中所建议的,您可能对每个月的持续时间感兴趣并且您不想对结果进行四舍五入。不幸的是,timedelta 对象在这种情况下对您不起作用,因为根据定义,时差不包含获取您感兴趣的月份持续时间所需的信息。

    你应该看看这里: Python: Difference of 2 datetimes in months 他们使用calendar 而不是dateutil 讨论解决方案。

    否则,如果您对近似(和四舍五入)的估计感到满意,您可以通过以下方式进行足够接近:

    DAYS_PER_MONTH = 30  # or 365.0 / 12.0 for more precision
    datetime_diff = date2 - date1
    print(datetime_diff.days / DAYS_PER_MONTH)  # '//' for floored result
    

    如果您想返回一些适用于您的数据的代码(但不是适用于所有数据,例如闰年、闰秒等),请查看此处:

    MONTH_NUM_DAYS = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
    YEAR_LENGTH = 365.25  # average year duration, including leap years
    
    def num_days_in_months(
            begin_month, end_month, month_duration=MONTH_NUM_DAYS):
        begin_month, end_month = sorted((begin_month, end_month))
        return sum(month_duration[begin_month:end_month])
    
    def get_num_months(begin_date, end_date, num_days_per_year=YEAR_LENGTH):
        begin_month = begin_date.month
        end_month = end_date.month
        month_diff = abs(end_month - begin_month)
        num_days = (end_date - begin_date).days
        num_days_within_year = num_days % num_days_per_year
        num_months = num_days // num_days_per_year
        num_days_max = num_days_in_months(begin_month, end_month)
        print(num_months, month_diff)
        if num_days_within_year < num_days_max:
            num_months += month_diff - 1
        else:
            num_months += month_diff
        return num_months
    

    【讨论】:

    • 这是 5 个月,因为增量实际上是 5 个月,30.5 天。第一天的时间是 12:00,第二天是隐含的 0:00。如果时间相同,您将获得 6 mos(例如,省略第一次或将第二次设置为 12:00)
    • 我明白了.. 我显然忽略了预期的行为不是round(num_months),而是floor(num_months),并且您对每个月的确切持续时间感兴趣,在这种情况下timedelta对象不是那里的选项,因此可能没有不涉及在每个月的持续时间内循环的解决方案
    • 我假设您知道地板操作,因为这也是您在回答中使用 // 所做的事情。
    • 谢谢,我已经编辑了答案以反映您的建议。
    • @norok2 你能用你的代码给出 exaqmple 日期吗?
    猜你喜欢
    • 1970-01-01
    • 2019-04-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多