如何在python中将整数列转换为标准小时时间? [英] how to convert a column of integer to standard hour time in python?

查看:535
本文介绍了如何在python中将整数列转换为标准小时时间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个像这样的数据框:

I have a data frame like this:

BuyTime        ID      SellTime
94650          1       94651
94717          1       94817
120458         2       114119

购买时间和出售时间类型是整数,但我想将它们转换为标准时间日期. 我已经用过

the buy time and sell time type are integer but i want to convert them to standard time date. I already used

 quote['SellTime'] = pd.to_datetime(quote['SellTime'], unit = 's')

,但是它给了类似1970-01-01的开始年份,这是不必要的. 我的数据应该是这样的:

but it gives a start year like 1970-01-01 to time which is not needed. my data should be like this:

BuyTime     Id     SellTime
09:46:50    1      09:46:51
09:47:17    1      09:48:17
12:04:58    2      11:41:19

同样使用此功能对我的数据大小效率不高:

also using this function regard to size of my data is not efficient:

 def format_time(value):
 t2 = str(value)
 if len(t2) == 5:
     return "0%s:%s:%s" % (t2[0], t2[1:3], t2[3:5])
 return "%s:%s:%s" % (t2[0:2], t2[2:4], t2[4:6])

推荐答案

我认为如果需要将输出作为string

I think you need if need output as strings zfill and str[] for select by positions:

t1 = quote['BuyTime'].astype(str).str.zfill(6)
t2 = quote['SellTime'].astype(str).str.zfill(6)
quote['BuyTime'] = t1.str[0:2] + ':' + t1.str[2:4] + ':' + t1.str[4:6]
quote['SellTime'] = t2.str[0:2] + ':' + t2.str[2:4] + ':' + t2.str[4:6]
print (quote)
    BuyTime  ID  SellTime
0  09:46:50   1  09:46:51
1  09:47:17   1  09:48:17
2  12:04:58   2  11:41:19

或者根据需要python times通过

Or if need python times add 0 by zfill, convert to datetimes and extract times:

t1 = quote['BuyTime'].astype(str).str.zfill(6)
t2 = quote['SellTime'].astype(str).str.zfill(6)
quote['BuyTime'] = pd.to_datetime(t1, format='%H%M%S').dt.time
quote['SellTime'] = pd.to_datetime(t2, format='%H%M%S').dt.time
print (quote)
    BuyTime  ID  SellTime
0  09:46:50   1  09:46:51
1  09:47:17   1  09:48:17
2  12:04:58   2  11:41:19

string的输出的替代方法是 strftime :

Alternative for strings outputs is strftime:

quote['BuyTime'] = pd.to_datetime(t1, format='%H%M%S').dt.strftime('%H:%M:%S')
quote['SellTime'] = pd.to_datetime(t2, format='%H%M%S').dt.strftime('%H:%M:%S')
print (quote)
    BuyTime  ID  SellTime
0  09:46:50   1  09:46:51
1  09:47:17   1  09:48:17
2  12:04:58   2  11:41:19

这篇关于如何在python中将整数列转换为标准小时时间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆