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

Converting/Modifying non-standard string into datetime for Python DataFrame

So I have a set of data for sales by month (not in order) but the string format for the data column comes out as month/day/year hour:minute

For example: 04/19/19 18:27 and it is a string object.

How am I able to convert this into datetime where I only take the month and day?

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

Also, how can I simply take only the month and convert it to an integer?

>Solution :

To convert it to a datetime, use pd.to_datetime():

df['date'] = pd.to_datetime(df['date'], format="%m/%d/%y %H:%M")

To get the month out of it, use this after you’ve run the above:

df['month'] = df['date'].dt.month

To convert it into a YYYY-MM format:

df['year-month'] = df['a'].dt.strftime('%Y-%m')
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