1

I'm trying to change one column of a pandas dataframe from a format like this: 162000 to 16:20:00 (%H%M%S)

I've tried this:

t = mydataframe['column name']
pd.to_datetime(t, format='%H%M%S')

But I get this error:

TypeError: 'long' object is unsliceable

However if I don't use the format parameter I get this:

1970-01-01 00:00:00.000162000

What's going on here?

EDIT:

t.dtype
Name: column name, dtype: int64

print t.head(5)
0    162000
1    161200
2    162400
3    163600
4    164800

t.to_dict()
{0: 162000,
 1: 161200,
 2: 162400,
 3: 163600,
 4: 164800, ...

EDIT2:

Ok, restarting the kernel of the notebook, solved that issue! Computers eh? :D

Ok, now I have this format:

1900-01-01 16:20:00

How can I change this so, that the to_datetime gives me only 16:20:00 ?

EDIT3:

Got it! Btw, the answer for my second question is here: How to change the datetime format in pandas

Community
  • 1
  • 1

1 Answers1

2

You need to use .dt.time to get the time portion of your new datetime object.

pd.to_datetime(t, format='%H%M%S').dt.time

You also need to reassign the output of the above to your dataframe. Either assign it to a new column, or reassign it back to the original column.

To assign it to the existing column:

mydataframe['column name'] = pd.to_datetime(t, format='%H%M%S').dt.time

To assign it to a new column:

mydataframe['new column'] = pd.to_datetime(t, format='%H%M%S').dt.time

In either case, you get a dataframe that looks like this

    Times
0   16:20:00
1   16:12:00
2   16:24:00
3   16:36:00
4   16:48:00
Andy
  • 49,085
  • 60
  • 166
  • 233
  • I had already found a way to do it with `.dt.strftime("%H:%M")`, but this one seems simpler :) Thanks ! – Richard Luso Dec 17 '16 at 05:15
  • 1
    @RichardLuso What you had found a way to do with `strftime` is turn your column into a string column. I.e. the reverse direction of the parse you'd previously done. You couldn't calculate on that. With @Andy's approach, those are genuine, calculate-able time objects. – Jonathan Eunice Dec 17 '16 at 05:25