Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

datetime
0830
0835
0840
0845

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

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading