How to avoid time being generated after subtracting timedelta

余生颓废 提交于 2020-01-24 20:15:50

问题


I have a dataframe which look like this as below

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

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?


回答1:


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

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

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'])


来源:https://stackoverflow.com/questions/52196505/how-to-avoid-time-being-generated-after-subtracting-timedelta

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!