How To Convert A Column Of Integer To Standard Hour Time In 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
Solution 1:
I think you need if need output as string
s 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:501 09:46:511 09:47:171 09:48:17212:04:58211:41:19
Or if need python times
add 0
by zfill
, convert to datetime
s and extract 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:501 09:46:511 09:47:171 09:48:17212:04:58211:41:19
Alternative for string
s 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
009:46:50109:46:51109:47:17109:48:17212:04:58211:41:19
Solution 2:
Assuming the date string only contains hour/minute/second (and minute/second are always 2 characters long, you could do something like this to parse the string using Python's modulo operator:
dateStr = '94522'
dateInt = int(dateStr)
sec = dateInt % 100
dateInt = dateInt - sec
min = dateInt % 10000
dateInt = dateInt - minmin /= 100
hour = dateInt / 10000
newDateStr = '{}:{}:{}'.format(hour, min, sec)
print'number={} formatted={}'.format(dateStr, newDateStr)
This will work for both 5 and 6 character long time strings.
Post a Comment for "How To Convert A Column Of Integer To Standard Hour Time In Python?"