问题有点简单。我的目标是计算两个日期(例如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:
TypeError:类'datetime.time'不能转换为datetime
TypeError: class 'datetime.time' is not convertible to datetime
当我将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'>不可转换为日期时间
发布评论