gpt4 book ai didi

python - 日期时间转换为年

转载 作者:太空宇宙 更新时间:2023-11-03 19:52:55 24 4
gpt4 key购买 nike

这是我当前的代码

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]

如何将以上内容更改为年份?

最佳答案

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

df['Age'] = df['Age'].dt.days #turn timedelta into int number of days
df['Age'] = df['Age']/365.25

后记,如果小数位数太多,您可以使用舍入。

这仅计算天数。如果你想要更精确,你甚至可以使用秒,1年为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

基本上,您的 Timedelta 有多种单位:天、小时、分钟、秒。您想将其转换为一个单位:年的 float 分数。一种方法是仅转换为可用单位之一,然后转换为年。因此:

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

关于python - 日期时间转换为年,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59714953/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com