0

I have pandas column row['date'] which contains date in format 11/05/2015. I am trying to insert it into mysql db but having problems due to incorrect format of date field data. It has to be converted into 2015-11-05 in order to be inserted. Without storing the new value in variable how can I convert the date into required format?

Current format: 11/05/2015
Required format: 2015-11-05
1

3 Answers 3

2

Is the current format mm/dd/yyyy? If so

from datetime import datetime
row['date'] = datetime.strptime(row['date'], '%m/%d/%Y').strftime('%Y-%m-%d')
Sign up to request clarification or add additional context in comments.

2 Comments

I didn't want to further clutter the code so here is what I did and this is ready by my sql query using .format. datetime.strptime(row['date'], '%m/%d/%Y').strftime('%Y-%m-%d')
You might even be able to send the datetime object to the database depending on how your MySQL adaptor works.
0

Use dateutil.parser,

This module offers a generic date/time string parser which is able to parse most known formats to represent a date and/or time.

Here is a MWE.

from dateutil.parser import parse

current_date = '11/05/2015'
required_date = parse(current_date).strftime('%Y-%m-%d')

PS: to explicitly distinguish between DM and MD, pass the argument dayfirst=True/False to parse, i.e. dayfirst=True represents DM and dayfirst=False represents MD.

2 Comments

Explicit is better than implicit. I'd say its better to be explicit about what format you are converting from. 11/05/2015 could be either dd/mm/yyyy or mm/dd/yyyy.
@Mat, thx, then add the argument dayfirst=False (the default value) to parse.
-1

This should do the job, w/o needing datetime:

"{2}-{0}-{1}".format(*(original_date.split("/")))

2 Comments

I think you're better off using datetime rather than mangling the string. Reading this line as is the intent is not clear.
Not disagreeing; just providing an option.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.