TypeError:< class'datetime.time'>不可转换为日期时间

编程入门 行业动态 更新时间:2024-10-27 20:27:16
本文介绍了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:

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'>不可转换为日期时间

本文发布于:2023-11-26 22:48:16,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1635518.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:转换为   日期   时间   lt   class

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!