python - Python:将索引的数据类型从对象更改为日期时间会删除时间(HH:MM:SS)
问题描述
我正在尝试从每天到每小时对我拥有的一些数据进行上采样。为此,我需要获取日期时间格式的索引,但由于以下问题,我陷入了困境。
我将我的 df 加载到:
df1 = pd.read_csv("DATA.CSV", index_col="DT")
df1.head(5)
这看起来不错,但数据类型是对象,我需要转换为日期时间。所以我尝试了:
df1.index = pd.to_datetime(df1.index)
df1.head(5)
哪个确实可以更改数据类型,但索引现在已经失去了它的时间部分:
有人能建议我如何制作数据类型日期时间并显示时间吗?有谁知道为什么时间会消失?可能是因为现在是 00:00:00?
解决方案
read the file as :
df1 = pd.read_csv("DATA.CSV")
then apply:
df['Date'] = pd.to_datetime(df['Date']).dt.strftime('%Y-%m-%d %H:%M:%S')
df.set_index('Date')
replace Date
column with the original date column name.
Note: this converts the index to string.
Another solution:
df1 = pd.read_csv("DATA.CSV", index_col="DT", parse_dates=['DT'])
df1.index = df1.index.strftime('%Y-%m-%d %H:%M:%S')
推荐阅读
- npm - 无法在 npm 脚本中正确配置 Autoprefixer
- amazon-web-services - 通过会话管理器连接到 Windows EC2 实例时出错
- pentaho - 使用日志从存储库运行 Pentaho 作业
- c# - 重命名文件就是重命名文件的扩展名
- java - 我正在尝试学习为 Java 中的 Discord 编写机器人,但出现错误:java.lang.ClassNotFoundException: net.dv8tion.jda.api.JDABuilder
- javascript - 使用生成的数组列表的输入值调用函数
- python - 如何区分 Django 模板中的两种形式?
- android - 清单看不到活动 - Android
- r - 有没有办法在 R 中选择性地收集网络数据?
- integromat - 基于 Integromat 场景创建脚本