如何避免在减去timedelta后产生时间 [英] How to avoid time being generated after subtracting timedelta

查看:29
本文介绍了如何避免在减去timedelta后产生时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个如下所示的数据框

I have a dataframe which look like this as below

Year Birthday OnsetDate
5             2018/1/1
5             2018/2/2

现在我使用 OnsetDate 列减去 Day 列

now I use the OnsetDate column subtract with the Day column

df['Birthday'] = df['OnsetDate'] - pd.to_timedelta(df['Day'], unit='Y')

但生日专栏的结果与时间混合,如下所示

but the outcome of the Birthday column is mixing with time just like below

Birthday
2013/12/31 18:54:00
2013/1/30 18:54:00

结果只是一个虚拟数据,我关注的是时间会导致操作后日期不准确.有什么办法可以避免产生时间,以便我可以得到准确的数据.

the outcome is just a dummy data, what I focused on this is that the time will cause inaccurate of date after the operation. What is the solution to avoid the time being generated so that I can get accurate data.

第二个问题,我将上述数据框合并到另一个数据框.

Second question, I merge the above dataframe to another data frame.

new.update(df)

和新"数据框生日列变成这样

and the 'new' dataframe Birthday column became like this

Birthday
1164394440000000000
1165949640000000000

所以实际上导致了这个,解决方案是什么?

so actually caused this and what is the solution?

推荐答案

第一个问题,你应该知道使用 pd.to_timedelta 不是一整年.如果打印,您可以看到 1 year = 365 days 05:49:12.

First question, you should know that is not a whole year by using pd.to_timedelta. If you print, you can see 1 year = 365 days 05:49:12.

print(pd.to_timedelta(1, unit='Y'))
365 days 05:49:12

如果想避免时间被生成,可以使用DateOffset.

If you want to avoid the time being generated, you can use DateOffset.

from pandas.tseries.offsets import DateOffset
df['Year'] = df['Year'].apply(lambda x: DateOffset(years=x))
df['Birthday'] = df['OnsetDate'] - df['Year']
                    Year  OnsetDate   Birthday
0  <DateOffset: years=5> 2018-01-01 2013-01-01
1  <DateOffset: years=5> 2018-02-02 2013-02-02

至于第二个问题是由列的类型引起的,可以使用pd.to_datetime来解决.

As for the second question is caused by the type of column, you can use pd.to_datetime to solve it.

new['Birthday'] = pd.to_datetime(new['Birthday'])

这篇关于如何避免在减去timedelta后产生时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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