Neil
Neil

Reputation: 8247

how to replace seconds to zero in pandas

I have following dataframe in pandas

  code     time
  1        003002
  1        053003
  1        060002
  1        073001
  1        073003

I want to generate following dataframe in pandas

  code     time        new_time
  1        003002      00:30:00
  1        053003      05:30:00
  1        060002      06:00:00
  1        073001      07:30:00 
  1        073003      07:30:00

I am doing it with following code

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

How can I do it in pandas?

Upvotes: 2

Views: 1104

Answers (2)

benlev
benlev

Reputation: 120

An option using astype:

pd.to_datetime(df_oclh.Time).astype('datetime64[m]').dt.time

'datetime64[m]' symbolizes the time we want to convert to which is datetime with minutes being the largest granulariy of time wanted. Alternatively you could use [s] for seconds (rid of milliseconds) or [H] for hours (rid of minutes, seconds and milliseconds)

Upvotes: 0

jezrael
jezrael

Reputation: 862681

Use Series.dt.floor:

df['time'] = pd.to_datetime(df['time'], format='%H%M%S').dt.floor('T').dt.time

Or remove last 2 values by indexing, then change format to %H%M:

df['time'] = pd.to_datetime(df['time'].str[:-2], format='%H%M').dt.time

print (df)
  code      time
0    1  00:30:00
1    1  05:30:00
2    1  06:00:00
3    1  07:30:00
4    1  07:30:00

Upvotes: 4

Related Questions