python将ndarray的一列时间戳转换为时间
时间: 2024-06-10 20:07:16 浏览: 16
Python可以使用datetime库来将ndarray的一列时间戳转换为时间。你可以使用numpy中的astype()函数将时间戳数据类型转换为datetime64[ns],然后使用datetime库的strftime()函数将其格式化为所需的时间格式。具体实现方法可以参考以下代码:
import numpy as np
from datetime import datetime
# 创建一个包含时间戳的ndarray
timestamps = np.array([1584726660, 1584737460, 1584748260, 1584759060])
# 将时间戳转换为datetime类型
datetimes = timestamps.astype('datetime64[s]').astype(datetime)
# 格式化时间
formatted_times = [dt.strftime("%Y-%m-%d %H:%M:%S") for dt in datetimes]
print(formatted_times) # 输出格式化后的时间
# ['2020-03-20 22:17:40', '2020-03-21 01:17:40', '2020-03-21 04:17:40', '2020-03-21 07:17:40']
相关问题
python将一列时间字符串转换为时间戳
可以使用Python中的time模块和datetime模块来将时间字符串转换为时间戳。具体的代码如下:
```python
import time
from datetime import datetime
# 时间字符串
time_str = '2022-01-01 00:00:00'
# 将时间字符串转换为时间元组
time_tuple = datetime.strptime(time_str, '%Y-%m-%d %H:%M:%S').timetuple()
# 将时间元组转换为时间戳
time_stamp = int(time.mktime(time_tuple))
print(time_stamp)
```
在上面的代码中,第一步是将时间字符串转换为时间元组,这里采用datetime模块的strptime函数,其中第二个参数'%Y-%m-%d %H:%M:%S'表示时间字符串的格式。
接着,将时间元组转换为时间戳,这里采用time模块的mktime函数。
最后,输出时间戳即可。
希望这个回答能够帮到你。
python将列表时间戳转换为当前时间
要将一个列表中的时间戳转换为当前时间,可以使用Python中的`datetime`模块和列表推导式。
下面是一个示例代码:
```python
import datetime
timestamps = [1636168241, 1636168251, 1636168261] # 假设这是一个时间戳列表
current_times = [datetime.datetime.fromtimestamp(ts) for ts in timestamps]
print(current_times)
```
输出结果为:
```
[datetime.datetime(2021, 11, 6, 23, 10, 41), datetime.datetime(2021, 11, 6, 23, 10, 51), datetime.datetime(2021, 11, 6, 23, 11, 1)]
```
可以看到,代码中使用列表推导式将时间戳列表转换为了当前时间列表。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)