DataFrame date column

0

I have this DataFrame and would like to separate the column from the date how do I do this?

    Data e Hora         Consumo(litros)  Valor Acumulado
0   2017-08-21 20:00:00              65               65
1   2017-08-21 21:00:00              81              146
2   2017-08-21 22:00:00              10              156
    
asked by anonymous 24.06.2018 / 02:21

1 answer

1

You should first transform the Data e Hora column to datetime

df['Data e Hora'] = pd.to_datetime(df['Data e Hora'])

to create the columns by using the dt.strftime convert the value of the Data e Hora column to a string in date format .

# Coluna 'Data'
df['Data'] = df['Data e Hora'].dt.strftime('%Y-%m-%d')
# Coluna 'Hora'
df['Hora'] = df['Data e Hora'].dt.strftime('%H:%M:%S')

Now it has the result:

          Data e Hora  Consumo(litros)    ...           Data      Hora
0 2017-08-21 20:00:00               65    ...     2017-08-21  20:00:00
1 2017-08-21 21:00:00               81    ...     2017-08-21  21:00:00
2 2017-08-21 22:00:00               10    ...     2017-08-21  22:00:00

If you want to remove the Data e Hora column and sort the columns by placing the Data column and the Hora column at startup:

# Remove a coluna 'Data e Hora'
del df['Data e Hora']
# Ordena as colunas
df = df[['Data', 'Hora', 'Consumo(litros)', 'Valor Acumulado']]

The result now is:

         Data      Hora  Consumo(litros)  Valor Acumulado
0  2017-08-21  20:00:00               65               65
1  2017-08-21  21:00:00               81              146
2  2017-08-21  22:00:00               10              156

See working at repl.it

The complete code:

import pandas as pd
df = pd.read_csv('DataFrame.csv', delimiter=";");

df['Data e Hora'] = pd.to_datetime(df['Data e Hora'])
df['Data'] = df['Data e Hora'].dt.strftime('%Y-%m-%d')
df['Hora'] = df['Data e Hora'].dt.strftime('%H:%M:%S')

del df['Data e Hora']
df = df[['Data', 'Hora', 'Consumo(litros)', 'Valor Acumulado']]

print(df)

References:

24.06.2018 / 04:57