2

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?

1
  • Just to confirm: last two lines should not be 12:30 and 12:00 but rather 00:30 and 00:00? Commented Sep 19, 2018 at 18:46

1 Answer 1

4

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
Sign up to request clarification or add additional context in comments.

8 Comments

How would you differentiate between 12 pm and 12 am? Or is 12 in the hour always 00?
its giving me ValueError: time data 0 does not match format '%H%M%S' (match) error
If they are integers, make them strings
There must be some times that don't match the format. You can also do pd.to_datetime(data.time, format='%H%M%S', errors='coerce').dt.time, which will return NaN in the rows where the format is not interpretable as a time
@sacul I have 0 in time column for which it should give 00:00:00
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.