繁体   English   中英

如何在python中将整数列转换为标准小时?

[英]how to convert a column of integer to standard hour time in python?

我有一个这样的数据框:

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

买入时间和卖出时间类型是整数,但我想将它们转换为标准时间日期。 我已经习惯了

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

但是它给了像1970-01-01这样的开始年份到了不需要的时间。 我的数据应该是这样的:

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

编辑:也使用此功能关于我的数据大小效率不高:

 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 s zfillstr[]用于选择位置:

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 timeszfill添加0 ,则转换为datetime s并提取time s:

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

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

假设日期字符串仅包含小时/分钟/秒(并且分钟/秒总是2个字符长,您可以使用Python的模运算符来解析字符串:

dateStr = '94522'
dateInt = int(dateStr)
sec = dateInt % 100
dateInt = dateInt - sec
min = dateInt % 10000
dateInt = dateInt - min
min /= 100
hour = dateInt / 10000

newDateStr = '{}:{}:{}'.format(hour, min, sec)
print 'number={} formatted={}'.format(dateStr, newDateStr)

这适用于5和6个字符的长字符串。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM