python - 将整数转换为时间格式
问题描述
我有以下数据框:
data = {"hours": [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]}
df = pd.DataFrame(data)
我一直在尝试获取以下时间格式:
1:00:00, 2:00:00 ... 12:00:00 etc
所以最后在打字时df.dtypes
我也会得到以下格式:datetime64[ns]
但不幸的是我没有成功。我尝试了以下方法:
df['new_hours'] = pd.to_datetime(df['hours'])
但它没有用。
解决方案
This works:
import pandas as pd
data = {"hours": [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]}
df = pd.DataFrame(data)
df['hours'] = (pd.Timestamp('now').normalize() + (pd.to_timedelta(df['hours'], unit='h'))).dt.time
print(df.head())
# hours
# 0 01:00:00
# 1 02:00:00
# 2 03:00:00
# 3 04:00:00
# 4 05:00:00
Explanation:
df['hours'] =
overwrites the Series named 'hours'(pd.Timestamp('now').normalize()
creates a datetime'now' and normalize() makes it a midnight datetime (e.g. today 00:00:00)+ (pd.to_timedelta(df['hours'],unit='h'))
creates a Timedelta object based on the integer in the 'hours' Series, unit parameter ensures its interpreted as hour. Adds this to the previous midnight datetime.).dt.time
takes the time of the datetime that was constructed in the previous 2 bull-its.
推荐阅读
- python - Python 3.7 日志记录:f-strings 与 %
- java - 子文件夹不是通过 java 通过 scp 命令复制的
- sql-server - 没有打开安装向导时如何删除 SQL Server 实例?
- javascript - 从 JS 对象字面量中的异步函数初始化的字段:它们会破坏并发性吗?
- c++ - 有什么方法可以在不使用内联的情况下停止多翻译
- structured-programming - 结构化和非结构化编程有什么区别?
- azure - Azure DevOps 发布到 Azure SQL,而不启用“允许访问 Azure 服务”
- java - JSONAssert.assertEquals:比较时忽略多个字段
- c# - 如何对发出的事件使用异步事件处理程序?
- python - 有没有办法使用 Python 通过使用 for 循环并从列表中调用来调用给定值列表的 API?