strptime() argument 1 must be str, not numpy.datetime64
时间: 2023-09-25 08:13:46 浏览: 49
如果你的时间字符串数组是NumPy的`datetime64`类型你可以使用`numpy.datetime64.astype()`方法将其转换为Python的`datetime.datetime`类型,然后再进行时间戳转换。以下是修改后的代码:
```python
import numpy as np
import datetime
timestamps = []
for item in list:
dt = np.datetime64(item).astype(datetime.datetime)
timestamp = dt.timestamp() * 1000 # 将秒转换为毫秒
timestamps.append(int(timestamp))
print(timestamps)
```
这段代码会将Py的`datetime64`类型转换为Python的`datetime.datetime`类型,然后再进行时间戳转换。输出的时间戳列表中的每个时间戳都是整数类型。
相关问题
TypeError: strptime() argument 1 must be str, not datetime.datetime
这个错误通常是因为你使用了 `datetime.datetime.strptime()` 函数的时候,第一个参数传入的类型不是字符串类型。
请检查你的代码,确保第一个参数是一个字符串类型的日期时间对象。如果你传入的是一个 `datetime.datetime` 类型的对象,你需要先将其转换为字符串类型,例如:
```
import datetime
now = datetime.datetime.now()
now_str = now.strftime("%Y-%m-%d %H:%M:%S") # 将 datetime 对象转换为字符串类型
parsed_date = datetime.datetime.strptime(now_str, "%Y-%m-%d %H:%M:%S") # 解析字符串类型的日期时间
```
这样就可以避免这个错误了。
strptime() argument 1 must be str, not Series
这个错误通常发生在你试图将一个 Pandas Series 对象作为 str 类型的参数传递给 Python 的 datetime.strptime() 方法时。datatime.strptime() 方法只接受 str 类型的参数,因此需要将 Series 对象转换为 str 类型。
下面是一种可能的解决方法:
```python
import pandas as pd
from datetime import datetime
# 创建一个示例 Series 对象
date_series = pd.Series(['2022-01-01', '2022-01-02', '2022-01-03'])
# 将 Series 对象转换为 str 类型,然后使用 datetime.strptime() 方法解析日期
dates = [datetime.strptime(d, '%Y-%m-%d') for d in date_series.astype(str)]
print(dates)
```
在上面的代码中,我们首先将 Series 对象转换为 str 类型,然后使用 datetime.strptime() 方法解析日期。请注意,我们使用了 astype() 方法将 Series 对象转换为 str 类型。在将 Series 对象转换为 str 类型之前,我们无法将其传递给 datetime.strptime() 方法。