Loading [MathJax]/extensions/tex2jax.js

【Python】Transforming datetime to date and time with pandas dateframe

Original Data

This code is to make sample dataframe.

01
02
03
04
import pandas as pd
import datetime as dt
 
df = pd.DataFrame([dt.datetime(2020,6,1,0,0,0),dt.datetime(2020,6,2,10,0,0),dt.datetime(2020,6,3,15,0,0)],columns=['datetimes'])
01
02
03
04
    datetimes
0   2020-06-01 00:00:00
1   2020-06-02 10:00:00
2   2020-06-03 15:00:00

Transforming dataframe to date and time.

It can realize to use lambda & apply functions like following.

01
02
df['dates'] = df['datetimes'].apply(lambda x : dt.date(x.year,x.month,x.day))
df['times'] = df['datetimes'].apply(lambda x : dt.time(x.hour,x.minute,x.second))
01
02
03
04
     datetimes       dates    times
0   2020-06-01 00:00:00 2020-06-01  00:00:00
1   2020-06-02 10:00:00 2020-06-02  10:00:00
2   2020-06-03 15:00:00 2020-06-03  15:00:00

If you want to get with string, these code is better.

01
02
df['dates'] = df['datetimes'].apply(lambda x : x.strftime('%Y/%m/%d'))
df['times'] = df['datetimes'].apply(lambda x : x.strftime('%H:%M:%S'))
01
02
03
04
    datetimes           dates           times
0   2020-06-01 00:00:00 2020/06/01  00:00:00
1   2020-06-02 10:00:00 2020/06/02  10:00:00
2   2020-06-03 15:00:00 2020/06/03  15:00:00

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *