Mainland
Mainland

Reputation: 4564

Python datetime to day and time

I want to extract day and time from a datetime index of a dataframe.

My code:

df.index = DatetimeIndex(['2020-07-07 19:03:38', '2020-07-08 18:50:40',
                '2020-07-24 4:20:13', '2020-07-25 4:20:13'],
              dtype='datetime64[ns]', name='datetime', freq=None)

print(df.index.strftime('%d %h:%m')

Is there a default way to get this like .date approach?

Upvotes: 3

Views: 106

Answers (1)

noah
noah

Reputation: 2776

Just use pd.to_datetime rather than the DatetimeIndex. And as Trenton McKinney pointed out in the comments it should be H and M in the strftime:

import pandas as pd
from datetime import datetime

data = {'stuff': [0,1,2,3]}
df = pd.DataFrame(data)

df.index = pd.to_datetime(['2020-07-07 19:03:38', '2020-07-08 18:50:40',
                '2020-07-24 4:20:13', '2020-07-25 4:20:13']).strftime('%d %H:%M')
                
print(df)

          stuff
07 19:03      0
08 18:50      1
24 04:20      2
25 04:20      3

Upvotes: 2

Related Questions