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

How to separate a sequence of numbers

How can I separate a sequence of numbers of a series in a dataframe like 20191110 into 2019-11-10 using python and pandas?

It should be a Date format

I tried: df = pd.to_datetime(df.date)

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

But it gave me a complete wrong date.
It turned 20191028 into: 1970-01-01 00:00:00.020191028

>Solution :

import datetime
datetime.datetime.strptime('20191110', "%Y%m%d").date()

#output
datetime.date(2019, 11, 10)

For a series you can do:

df['A'] = df['A'].dt.strftime('%Y-%m-%d')  # Data type of the series will become object(string)

OR

df['A'] = pd.to_datetime(df['A']).dt.date.astype('datetime64[ns]')
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