Python – How to convert a list of integers to standard hour time in python?

How to convert a list of integers to standard hour time in python?… here is a solution to the problem.

How to convert a list of integers 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 types are integers, but I want to convert them to standard time dates.
I’ve used it

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

But it gives a start year like 1970-01-01 to give unwanted time.
My data should look 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

Edit:
It’s not efficient to use this feature in terms of my data size as well:

 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])

Solution

If the output is required as strings zfill, I guess you need to select by location with str[].

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

Or add 0 by if you need python time >zfill , converted to datetime 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:50   1  09:46:51
1  09:47:17   1  09:48:17
2  12:04:58   2  11:41:19

An alternative to string output 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

Related Problems and Solutions