python - 将字符串转换为 HH :MM time in Python

标签 python pandas datetime

我是 Python 新手,如果这是一个简单的修复,我深表歉意。

我目前有一列时间存储为字符串,当我查看数据帧时,如下所示:

bus_no   time
Bus1     2.0
Bus2     840.0
Bus3     2340.0
Bus4     15.0
Bus5     1205.0
Bus6     1304.0
Bus7     1620.0
Bus8     9.0

因此 9.0 相当于 00:09、1620 到 16:20。 (这是一个相当大的数据集,包含更多字段,因此我创建了该示例以轻松显示它所显示的格式)

每次我尝试将其转换为时间时,它也会形成一个日期并将部分时间合并到日期中,从而产生不准确的输出。任何帮助将不胜感激。

最佳答案

我认为你需要timedelta s:

#remove NaNs rows in time column if necessary
#df = df.dropna(subset=['time'])
#or replace NaNs to 0
#df['time1'] = df['time1'].fillna(0)

#convert to int, then str and add 0 
s = df['time'].astype(int).astype(str).str.zfill(4)
#add : twice
df['time1'] = s.str[:2] + ':' + s.str[2:] + ':00'
#convert to timedeltas
df['time2'] = pd.to_timedelta(df['time1'])
print (df)
  bus_no    time     time1    time2
0   Bus1     2.0  00:02:00 00:02:00
1   Bus2   840.0  08:40:00 08:40:00
2   Bus3  2340.0  23:40:00 23:40:00
3   Bus4    15.0  00:15:00 00:15:00
4   Bus5  1205.0  12:05:00 12:05:00
5   Bus6  1304.0  13:04:00 13:04:00
6   Bus7  1620.0  16:20:00 16:20:00
7   Bus8     9.0  00:09:00 00:09:00

关于python - 将字符串转换为 HH :MM time in Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47097447/

相关文章:

python - 如何在django中的单个 View 中显示多个ForeignKey过滤项?

python - 如何将机器学习 (Tensorflow) 预测导出到 csv 文件?

python - 将十进制时间戳转换为日期时间时如何保留微秒?

java - 减去 1ms 会导致意外行为

sql - 在 SQL Server 中获取日期范围内的所有日期

python 3类型模块

python - 绘制 keras 自定义模型时,“ListWrapper”对象没有属性 'name'

python - 在 python pandas 的数据框中使用选定的列为每一行数据创建哈希值

python - Pandas 将索引排序为整数

python - Pandas :根据在其他列上应用字符串条件创建列