Home > Net >  pandas how to convert (%Y-%d-%m %H:%M) to number or string (HM)
pandas how to convert (%Y-%d-%m %H:%M) to number or string (HM)

Time:08-26

I have a df[datetime] looks like this:

    2020-07-13 08:30:00
    2020-07-13 08:35:00
    2020-07-13 08:40:00
    2020-07-13 08:45:00

You can have it by run this code:

import pandas as pd
from io import StringIO
 
StringData = StringIO("""datetime
       2020-07-13 08:30:00
       2020-07-13 08:35:00
       2020-07-13 08:40:00
       2020-07-13 08:45:00
    """)
 
df = pd.read_csv(StringData)
 
print(df)

My question is how can I convert it to numbers that only keep hours and numbers, the ideal output should like:

datetime
0830
0835
0840
0845

the type of it need be number or string. Any friend can help?

CodePudding user response:

Let us try

df['time'] = pd.to_datetime(df['datetime']).dt.strftime('%H%M')
Out[1031]: 
0    0830
1    0835
2    0840
3    0845
Name: datetime, dtype: object
  • Related