Format Time in a Python data frame

Asked

Viewed 2,125 times

4

I’m trying to format the column that brings the hours with milesimos, that is, to take milesimos and visualize hh:mm:ss only.

inserir a descrição da imagem aqui

3 answers

6


I believe the simplest way is to recreate all column values with a datetime.time object that copies the time, minute and seconds and ignores the microseconds of the original column.

I like to put code that other people can run from scratch, without having to think about how to create a dataframe where it can be applied - the example would be:

import datetime as dt, pandas as pd

z = pd.DataFrame({"hora": [dt.time(23,59,37, 159245)]}) 

at the ipython terminal::

In [566]: print(z)                                                                                                     
              hora
0  23:59:37.159245

There, to recreate the column "time":

z["hora"] = z["hora"].apply(lambda t:dt.time(t.hour, t.minute, t.second)) 

And the result:

In [568]: print(z)                                                                                                     
       hora
0  23:59:37

What has been done: the method apply of Series and Dataframes takes as a first argument a function that takes the row or column (in the case of a dataframe) or the value of the cell (in the case of a series) and returns a result. This result is used as the value of a new cell. In this case, set a "lambda" function that receives a value "t", which is assumed to be a datetime.time, and generates another datetime.time, but using only the information of hour, minute and seconds. The "time" column in the original dataframe is replaced by the new one, with the sign of "=".

(In your example date frame, of course, just do the same for the column "Original Time")

Another important detail: this method effectively changes the values in the column, not just the visualization of it. If you want to keep the original values and change only the presentation, the approach has to be different.

  • Thank you very much, it worked. Abs.

3

Assuming you have the time on string, you can convert to an object datetime, making:

from datetime import datetime
hora_string = '18:34:23.123'  # Valor da primeira linha
objeto_datetime = datetime.strptime(hora_string, '%H:%M:%S.%f')

Then to convert back to string in the desired format (more formats here), do:

objeto_datetime.strftime('%H:%M:%S')

Will result in:

'18:34:23'

More details on python documentation.

  • 3

    Good answer, but in this case it has a Pandas dataframe - the approach with Pandas objects is quite different from the one used in pure Python - in general, we have at least to worry about using the methods of Pandas objects themselves that allow to perform the desired operations. (In this case it has a column whose elements are already objects compatible with the datetime.time python)

  • I agree 100% with you @jsbueno.

  • @Thiagokrempser I can add a suggestion?

  • Of course I do, @Terry!

  • @Thiagokrempser The moderators said that my edition should be an answer

1

You can convert the column Original Time for datetime using the function (1)to_datetime and extracting only the hour, minute and second with (2)strftime

df['somente Horas'] = pd.to_datetime(df['Hora Original'], format= '%H:%M:%S.%f') \
                        .apply(lambda x: x.strftime('%H:%M:%S'))

Browser other questions tagged

You are not signed in. Login or sign up in order to post.