dataframe一列时间戳数据转换为字符串
时间: 2023-11-27 08:05:33 浏览: 62
可以使用 pandas 库中的 strftime 函数将时间戳列转换为字符串格式。具体实现如下:
```
import pandas as pd
# 假设时间戳列名为 timestamp,数据框名称为 df
df['timestamp'] = pd.to_datetime(df['timestamp'], unit='s')
df['time_str'] = df['timestamp'].dt.strftime('%Y-%m-%d %H:%M:%S')
```
其中,`pd.to_datetime` 函数将时间戳转换为 datetime 格式,`dt.strftime` 函数将 datetime 格式转换为字符串格式,并指定了输出格式为 `%Y-%m-%d %H:%M:%S`。最后将转换后的字符串保存在新的一列 `time_str` 中。
相关问题
如何将dataframe第一列的字符串转为时间戳
可以使用 pandas 的 to_datetime() 方法将字符串转换为时间戳,具体代码如下:
```python
import pandas as pd
df = pd.read_csv('data.csv')
df['date'] = pd.to_datetime(df['date'])
```
其中,'data.csv' 是你的数据文件名,'date' 是你要转换的列名。
dataframe 数据时间戳格式转化秒数
假设你的 DataFrame 中有一个名为 `timestamp` 的列,其中包含时间戳,可以按照以下方式将时间戳转换为秒数:
```python
import pandas as pd
df = pd.DataFrame({'timestamp': ['2022-01-01 10:00:00', '2022-01-01 10:01:00', '2022-01-01 10:02:00']})
df['timestamp'] = pd.to_datetime(df['timestamp']) # 将字符串转换为时间戳格式
df['seconds'] = df['timestamp'].astype(int) / 10**9 # 将时间戳转换为秒数
```
在上面的代码中,我们首先使用 `pd.to_datetime` 将字符串转换为时间戳格式,然后使用 `astype(int)` 将时间戳转换为整数,最后除以 $10^9$ 得到秒数。结果如下:
```
timestamp seconds
0 2022-01-01 10:00:00 1.640729e+09
1 2022-01-01 10:01:00 1.640729e+09
2 2022-01-01 10:02:00 1.640729e+09
```
注意,由于时间戳的精度为纳秒级别,因此在将其转换为秒数时需要除以 $10^9$。
相关推荐
![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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)