r0xette
r0xette

Reputation: 908

Convert date format to insert into mysql db

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

Upvotes: 0

Views: 3738

Answers (3)

SparkAndShine
SparkAndShine

Reputation: 18047

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.

Upvotes: 0

Scott Hunter
Scott Hunter

Reputation: 49921

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

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

Upvotes: -1

Mat
Mat

Reputation: 1403

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')

Upvotes: 2

Related Questions