Neil
Neil

Reputation: 8247

how to convert integer time to time object in python

I have following pandas dataframe

  code     time
  1        170000
  2        70000
  3        123000
  4        120000

My desired dataframe is following

  code     time       new_time 
  1        170000     17:00:00
  2        70000      07:00:00
  3        123000     00:30:00
  4        120000     00:00:00

I am doing following in python

data['new_time'] = [time.strftime('%H:%M:%S', time.gmtime(x)) for x in data['time']]
data['new_time'] = pd.to_datetime(data['new_time']).dt.time

It's giving me some weird conversion. How can I do it?

Upvotes: 2

Views: 537

Answers (1)

sacuL
sacuL

Reputation: 51425

Use the format argument in pd.to_datetime (no need for the list comprehension or the time module):

data['new_time'] = pd.to_datetime(data.time, format='%H%M%S').dt.time

>>> data
   code    time  new_time
0     1  170000  17:00:00
1     2   70000  07:00:00
2     3  123000  12:30:00
3     4  120000  12:00:00

Upvotes: 4

Related Questions