I have a following question. I have a date_time column in my dataframe (and many other columns).
df["Date_time"].head()
0    2021-05-15 09:54
1    2021-05-27 17:04
2    2021-05-27 00:00
3    2021-05-27 09:36
4    2021-05-26 18:39
Name: Date_time, dtype: object
I would like to split this column into two (date and time).
I use this formula that works fine:
df["Date"] = ""
df["Time"] = ""
def split_date_time(data_frame):
    for i in range(0, len(data_frame)):
        df["Date"][i] = df["Date_time"][i].split()[0]
        df["Time"][i] = df["Date_time"][i].split()[1]
split_date_time(df)
But is there a more elegant way? Thanks
dt accessor can give you date and time separately:
df["Date"] = df["Date_time"].dt.date
df["Time"] = df["Date_time"].dt.time
to get
>>> df
            Date_time        Date      Time
0 2021-05-15 09:54:00  2021-05-15  09:54:00
1 2021-05-27 17:04:00  2021-05-27  17:04:00
2 2021-05-27 00:00:00  2021-05-27  00:00:00
3 2021-05-27 09:36:00  2021-05-27  09:36:00
4 2021-05-26 18:39:00  2021-05-26  18:39:00
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With