小能豆

如何将 python datetime.timedelta 转换为年份?

py

我需要检查自某个日期以来是否已经过去了 n 年。我正在使用模块timedelta中的datetime数据,但我不知道如何将其转换为年份。


阅读 27

收藏
2024-09-29

共1个答案

小能豆

检查是否ntimedelta,你可以比较n年。365.25

from datetime import datetime, timedelta

# Example date
given_date = datetime(
given_da
2010, 1, 1)
n = 
n 
5  # Number of years

# Current date
current_date = datetime.now()


current_date = datetime.no

current_date = d
# Calculate the difference in days
difference = current_date - given_date


difference = current_date - given

difference = current_date

difference = cur

differ
# Check if the difference is greater than or equal to n years
if difference >= timedelta(days=n * 365.25):


print(f"{n} years have passed since {given_date.date()}.")

els
else:

    pr
print(f"{n} years have not yet passed since {given_date.date()}.")

此代码检查n年份是否given_date通过 contimedelta

2024-09-29