简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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