'Split date and hour from a pandas serie

I have this DF that contains a column called data, on the format: "%Y-%m-%d %H:%M:%S.%f" and I'd like to get only the data format, like: "%Y-%m-%d". I made this code, but the date doesn't match with the original column.

for d in df['data']:
  data, hora = d.split(' ')
  df['DATA'] = data
  df['HORA'] = hora


Solution 1:[1]

You can convert to datetime object; then use dt.strftime:

df['data'] = pd.to_datetime(df['data'])
df['date'] = df['data'].dt.strftime('%Y-%m-%d')
df['hour'] = df['data'].dt.strftime('%H:%M:%S')

Output:

                       data        DATA          HORA        date      hour
0   2022-01-01 00:10:00.000  2022-01-31  21:41:59.999  2022-01-01  00:10:00
1   2022-01-01 03:39:59.999  2022-01-31  21:41:59.999  2022-01-01  03:39:59
2   2022-01-01 05:42:00.000  2022-01-31  21:41:59.999  2022-01-01  05:42:00
3   2022-01-01 06:19:00.000  2022-01-31  21:41:59.999  2022-01-01  06:19:00
4   2022-01-02 06:12:59.999  2022-01-31  21:41:59.999  2022-01-02  06:12:59
..                      ...         ...           ...         ...       ...
491 2022-01-30 23:47:59.999  2022-01-31  21:41:59.999  2022-01-30  23:47:59
492 2022-01-31 00:17:00.000  2022-01-31  21:41:59.999  2022-01-31  00:17:00
493 2022-01-31 02:49:00.000  2022-01-31  21:41:59.999  2022-01-31  02:49:00
494 2022-01-31 20:22:00.000  2022-01-31  21:41:59.999  2022-01-31  20:22:00
496 2022-01-31 21:41:59.999  2022-01-31  21:41:59.999  2022-01-31  21:41:59

[409 rows x 5 columns]

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1