[英]How to subtract time in Pandas DataFrame
How can I substract checkout_time
from purchase_time
to find total time spent on the website? 我怎样才能。减去
checkout_time
从purchase_time
找到花在网站上的总时间? Please view the DataFrame here: Table 请在此处查看数据框: 表
I used the following code but it gives me an error. 我使用了以下代码,但它给了我一个错误。 The format for time is 1/26/2017 14:44:
时间格式为1/26/2017 14:44:
df['time_to_purchase'] = df.purchase_time - df.checkout_time
However I receive the following error: 但是,我收到以下错误:
TypeError: unsupported operand type(s) for -: 'float' and 'str'
You'll need to convert the dtype of the columns to something that Pandas can recognize for doing datetime arithmetic: 您需要将列的dtype转换为Pandas可以识别的日期时间算法:
fmt = '%m/%d/%Y %H:%M' # or: infer_datetime_format=True
df['purchase_time'] = pd.to_datetime(df['purchase_time'],
format=fmt,
errors='coerce')
df['checkout_time'] = pd.to_datetime(df['checkout_time'],
format=fmt,
errors='coerce')
Using errors='coerce'
in pd.to_datetime
will force unrecognized/unparseable dates to become NaT
("not a time"). 在
pd.to_datetime
使用errors='coerce'
将迫使无法识别/无法解析的日期变为NaT
(“不是时间”)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.