data['逾期']=data['用车时间'].apply(lambda x:(datetime.now().strftime('%Y-%m-%d %H:%M:%S')-pd.to_datetime(x).strftime('%Y-%m-%d %H:%M:%S')).dt.days)返回unsupported operand type(s) for -: 'str' and 'str'
时间: 2023-08-27 09:04:03 浏览: 68
这个错误是因为`datetime.now().strftime('%Y-%m-%d %H:%M:%S')`和`pd.to_datetime(x).strftime('%Y-%m-%d %H:%M:%S')`都返回了字符串类型,不能直接相减。
应该把这两个字符串类型的对象转换为`datetime`类型的对象,然后再相减,最后使用`.days`方法获取相差的天数。修改代码如下:
```python
from datetime import datetime
import pandas as pd
data['逾期'] = data['用车时间'].apply(lambda x: (datetime.now() - pd.to_datetime(x)).days)
```
这样就可以成功计算逾期天数了。
相关问题
alldata3['datetime']=alldata3['datetime'].apply(lambda x:datetime.strptime(x,'%Y-%m-%d %H:%M:%S'))出现错误strptime() argument 1 must be str, not Timestamp怎么办
这个错误提示表明你传递给 `datetime.strptime()` 函数的参数应该是一个字符串,但实际上它是一个 Pandas DataFrame 中的时间戳数据类型。要解决这个问题,你可以使用 `pandas.Series.dt.strftime()` 函数将时间戳格式化为字符串,然后再使用 `datetime.strptime()` 函数将其转换为 datetime 对象。以下是一个示例代码:
```python
import pandas as pd
from datetime import datetime
alldata3['datetime'] = pd.to_datetime(alldata3['datetime']) # 先将时间戳转换为 Pandas 中的 datetime 对象
alldata3['datetime'] = alldata3['datetime'].dt.strftime('%Y-%m-%d %H:%M:%S') # 格式化为字符串
alldata3['datetime'] = alldata3['datetime'].apply(lambda x:datetime.strptime(x,'%Y-%m-%d %H:%M:%S')) # 转换为 datetime 对象
```
这段代码首先使用 `pd.to_datetime()` 函数将时间戳列转换为 Pandas 中的 datetime 对象,然后使用 `strftime()` 函数将其格式化为字符串,最后使用 `strptime()` 函数将字符串转换为 datetime 对象。
df['hour'] = df['时间列名'].apply(lambda x: datetime.strptime(x, '%Y-%m-%d %H:%M:%S').hour)这句代码什么意思
这句代码是针对一个名为df的DataFrame进行的操作。它的作用是将时间列(假设列名为“时间列名”)中的时间字符串转换成小时数,并将结果存储到名为“hour”的新列中。
具体来说,代码中的 lambda 表达式接受时间列中的每一个时间字符串作为输入,将其转换成一个 datetime 对象,再从该对象中提取小时数并返回。datetime.strptime() 方法根据给定的格式字符串将时间字符串解析成 datetime 对象。'%Y-%m-%d %H:%M:%S' 是一个时间格式字符串,其中各个字符的含义分别为:
- %Y:年份,4位数字
- %m:月份,2位数字
- %d:日期,2位数字
- %H:小时数,24小时制,2位数字
- %M:分钟数,2位数字
- %S:秒数,2位数字
最后,apply() 方法将 lambda 表达式应用到时间列中的每一个时间字符串上,并将返回的小时数存储到名为“hour”的新列中。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)