在Python中将字符串转换为HH:MM时间

2024-03-29 13:48:51 发布

您现在位置:Python中文网/ 问答频道 /正文

我是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。(这是一个相当大的数据集,有更多的字段,所以我创建了这个示例,以方便地显示它所显示的格式)

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


Tags: 数据no字符串time时间bus新手bus1
3条回答

使用:

def get_time(s):
    s = s.replace('.0','')
    time_type = len(s)
    if len(s) == 1:
        return '00:0%s'%s
    elif len(s) == 2:
        return '00:%s'%s
    elif len(s) == 3:
        return '0%s:%s'%(s[0:1], s[1:3])
    elif len(s) == 4:
        return '%s:%s'%(s[0:2], s[2:4])

首先,为了使字符串更加一致,可以使用str.zfill(x)使它们具有相同的长度。例如:

"9.0".zfill(6)

会给你“0009.0”。然后,你可以做一些类似的事情

^{pr2}$

将其转换为“HH:MM”格式。在

我想你需要^{}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

相关问题 更多 >