DataFrame 时间列中如何转换为时间戳格式并只保留年月日
时间: 2024-01-12 11:03:17 浏览: 42
可以使用 pandas 中的 `to_datetime()` 方法将 DataFrame 中的时间列转换为时间戳格式,然后使用 `dt.date` 方法只保留年月日。示例代码如下:
```python
import pandas as pd
# 假设你的 DataFrame 叫做 df,时间列叫做 time
df['time'] = pd.to_datetime(df['time']).dt.date
print(df['time'])
```
这将把 DataFrame 中的时间列转换为时间戳格式并只保留年月日,然后输出。
相关问题
python将dataframe中的1683829797列转换为年月日时分秒的格式(datetime类型)
可以使用pandas中的to_datetime函数来将DataFrame中的某一列转换为datetime类型。
假设你的数据框为df,你要将列名为1683829797的列转换为datetime类型,可以使用以下代码:
```
df['1683829797'] = pd.to_datetime(df['1683829797'], unit='s')
```
其中,参数unit='s'表示该列的数据是以秒为单位的时间戳。如果该列的时间单位不是秒,可以根据实际情况调整该参数,如unit='ms'表示毫秒。
怎么样在下面这段代码中x轴标签只保留年月日axes.set_xticks(df_time[::50]) axes.set_xticklabels(df_time[::50],rotation=45)
要保留年月日,可以使用 `strftime` 函数将时间戳格式化为只包含年月日的字符串。修改代码如下:
```python
import matplotlib.pyplot as plt
import pandas as pd
# 生成示例数据
df_time = pd.date_range('2022-01-01', '2022-12-31', freq='H')
df_value = pd.DataFrame({'value': np.random.rand(len(df_time))}, index=df_time)
fig, ax = plt.subplots()
ax.plot(df_value)
ax.set_xticks(df_time[::50])
ax.set_xticklabels([t.strftime('%Y-%m-%d') for t in df_time[::50]], rotation=45)
plt.show()
```
其中,`[t.strftime('%Y-%m-%d') for t in df_time[::50]]` 表示将 `df_time[::50]` 中每个时间戳对象转化为字符串,格式为 `%Y-%m-%d`,即只包含年月日,然后作为标签文本传递给 `ax.set_xticklabels` 函数。