不可转换为日期时间

不可转换为日期时间

本文介绍了TypeError:< class'datetime.time'>不可转换为日期时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题有点简单。我的目标是计算两个日期(例如A和B)之间的天差。

这些是我的尝试:

The problem is somewhat simple. My objective to to compute the days difference between two dates, say A and B.
These are my attempts:

df['daydiff'] = df['A']-df['B']

df['daydiff'] = ((df['A']) - (df['B'])).dt.days

df['daydiff'] = (pd.to_datetime(df['A'])-pd.to_datetime(df['B'])).dt.days

这些功能以前对我有用,但由于某种原因,我一直在使用这次错误:

These works for me before but for some reason, I'm keep getting this error this time:

当我将df导出到excel时,日期就可以了。任何想法?

When I export the df to excel and the date works just fine. Any thought?

推荐答案

使用pd.Timestamp处理格式化时间中的尴尬差异。

Use pd.Timestamp to handle the awkward differences in your formatted times.

df['A'] = df['A'].apply(pd.Timestamp)  # will handle parsing
df['B'] = df['B'].apply(pd.Timestamp)  # will handle parsing
df['day_diff'] = (df['A'] - df['B']).dt.days

当然,如果您不想更改df ['A']和df ['B ']在要输出的DataFrame中,您可以单行执行。

Of course, if you don't want to change the format of the df['A'] and df['B'] within the DataFrame that you are outputting, you can do this in a one-liner.

df['day_diff'] = (df['A'].apply(pd.Timestamp) - df['B'].apply(pd.Timestamp)).dt.days

这将使您之间的间隔时间为整数。

This will give you the days between as an integer.

这篇关于TypeError:< class'datetime.time'>不可转换为日期时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 10:15