Python 日期时间转换为年

Python 日期时间转换为年,python,pandas,Python,Pandas,这是我当前的代码 from datetime import datetime as dt df['Age'] = datetime.datetime.now()-pd.to_datetime(df[['Day','Month','Year']]) 但我的结果是 0 3380 days 10:37:40.303097 1 3512 days 10:37:40.303097 2 3131 days 10:37:40.303097 3 3739 days 10:37:40.3

这是我当前的代码

from datetime import datetime as dt
df['Age'] = datetime.datetime.now()-pd.to_datetime(df[['Day','Month','Year']])
但我的结果是

0    3380 days 10:37:40.303097
1    3512 days 10:37:40.303097
2    3131 days 10:37:40.303097
3    3739 days 10:37:40.303097
4    4550 days 10:37:40.303097
5    3204 days 10:37:40.303097
6    3813 days 10:37:40.303097
7    5819 days 10:37:40.303097
8    4532 days 10:37:40.303097
9    2444 days 10:37:40.303097
10   2664 days 10:37:40.303097
11   5527 days 10:37:40.303097
12   3706 days 10:37:40.303097
Name: Age, dtype: timedelta64[ns]

我怎样才能将上面的时间改为年呢?

我似乎无法将时间增量格式化为年-也就是说,你可以使用一个合适的近似值,即天-1年=365.25天

df['Age'] = df['Age'].dt.days #turn timedelta into int number of days
df['Age'] = df['Age']/365.25
如果小数位数太多,可以使用Round

这只算几天。如果您想要更高的精度,您甚至可以在一年内使用31556952秒:

df['Seconds'] = df.Age.dt.days*24*3600+df.Age.dt.seconds #turn timedelta into int number of seconds
df['Years'] = df.Seconds/31556952
基本上,你的时间增量有很多单位:天、小时、分钟、秒。你想把它转换成一个单位:浮动分数年。一种方法是只转换成一个可用单位,然后再转换成年。因此:

x = pd.Timedelta('3706 days 10:37:40.303097')
x.seconds
>>38260
x.days*24*3600+x.seconds
>>320236660 #Number of seconds in the Timedelta
(x.days*24*3600+x.seconds)/31556952 #Divided by the number of seconds in a year
>>10.14789577903468

我似乎无法将Timedelta格式设置为年,也就是说,您可以使用天的近似值-1年=365.25天

df['Age'] = df['Age'].dt.days #turn timedelta into int number of days
df['Age'] = df['Age']/365.25
如果小数位数太多,可以使用Round

这只算几天。如果您想要更高的精度,您甚至可以在一年内使用31556952秒:

df['Seconds'] = df.Age.dt.days*24*3600+df.Age.dt.seconds #turn timedelta into int number of seconds
df['Years'] = df.Seconds/31556952
基本上,你的时间增量有很多单位:天、小时、分钟、秒。你想把它转换成一个单位:浮动分数年。一种方法是只转换成一个可用单位,然后再转换成年。因此:

x = pd.Timedelta('3706 days 10:37:40.303097')
x.seconds
>>38260
x.days*24*3600+x.seconds
>>320236660 #Number of seconds in the Timedelta
(x.days*24*3600+x.seconds)/31556952 #Divided by the number of seconds in a year
>>10.14789577903468

这回答了你的问题吗
df['Age']=df['Age'].apply(lambda x:x.year)
这是您需要的吗这回答了您的问题吗?我尝试了“df['Age']=df['Age'].apply(lambda x:x.year)”并得到了这个错误,而不是“'Timedelta'对象没有属性'year'”,这是否回答了您的问题
df['Age']=df['Age'].apply(lambda x:x.year)
这是您需要的吗这回答了您的问题吗?我尝试了“df['Age']=df['Age'].apply(lambda x:x.year)”并得到了这个错误,取而代之的是“'Timedelta'对象没有属性'year'”。使用代码,我得到了'Age'作为这个值9天06:10:02.372658如何取整它?我得到一个错误,单位是天,而不是年使用代码,我得到的“年龄”是这个值9天06:10:02.372658我如何舍入它?我得到一个错误,而且单位是天而不是年