Python timedelta多年 [英] Python timedelta in years

查看:138
本文介绍了Python timedelta多年的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要检查一些日期以后是否有几年的时间。目前,我从 datetime 模块中得到了 timedelta ,我不知道如何将其转换为多年。 p>

I need to check if some number of years have been since some date. Currently I've got timedelta from datetime module and I don't know how to convert it to years.

推荐答案

你需要多于$ code> timedelta 您还需要知道开始(或结束)日期。 (这是一个闰年的事情。)

You need more than a timedelta to tell how many years have passed; you also need to know the beginning (or ending) date. (It's a leap year thing.)

你最好的选择是使用 dateutil.relativedelta 对象,但这是第三方模块。如果你想知道从某个日期(默认为现在)的 datetime n 年,你可以做以下::

Your best bet is to use the dateutil.relativedelta object, but that's a 3rd party module. If you want to know the datetime that was n years from some date (defaulting to right now), you can do the following::

from dateutil.relativedelta import relativedelta

def yearsago(years, from_date=None):
    if from_date is None:
        from_date = datetime.now()
    return from_date - relativedelta(years=years)

如果你想坚持使用标准库,答案有点复杂:

If you'd rather stick with the standard library, the answer is a little more complex::

from datetime import datetime
def yearsago(years, from_date=None):
    if from_date is None:
        from_date = datetime.now()
    try:
        return from_date.replace(year=from_date.year - years)
    except ValueError:
        # Must be 2/29!
        assert from_date.month == 2 and from_date.day == 29 # can be removed
        return from_date.replace(month=2, day=28,
                                 year=from_date.year-years)

如果是2/29和18年前没有2/29,这个功能将返回2/28。如果你宁愿返回3/1,只需更改最后一个返回语句来阅读::

If it's 2/29, and 18 years ago there was no 2/29, this function will return 2/28. If you'd rather return 3/1, just change the last return statement to read::

    return from_date.replace(month=3, day=1,
                             year=from_date.year-years)

你的问题最初说你想知道自从某个日期以来已经有多少年了。假设你想要一个整数年,你可以猜测每年365.25天,然后检查使用上面定义的 yearsago 函数之一::

Your question originally said you wanted to know how many years it's been since some date. Assuming you want an integer number of years, you can guess based on 365.25 days per year and then check using either of the yearsago functions defined above::

def num_years(begin, end=None):
    if end is None:
        end = datetime.now()
    num_years = int((end - begin).days / 365.25)
    if begin > yearsago(num_years, end):
        return num_years - 1
    else:
        return num_years

这篇关于Python timedelta多年的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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