将 timedelta 转换为年? [英] Convert timedelta to years?

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

问题描述

我需要检查自某个日期以来是否已经过了若干年.目前,我从 datetime 模块获得了 timedelta,但我不知道如何将其转换为年.

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.

推荐答案

你需要的不仅仅是一个 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 对象,但那是第 3 方模块.如果您想知道从某个日期开始 n 年的 datetime(默认为现在),您可以执行以下操作::

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,只需将最后一个 return 语句更改为 read::

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.2425 天进行猜测,然后使用上面定义的 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.2425 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.2425)
    if begin > yearsago(num_years, end):
        return num_years - 1
    else:
        return num_years

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

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