JamesHudson81
JamesHudson81

Reputation: 2273

Changing df column format

I have the following dict:

diction= [
    {
        "name": "x",
        "no": 10,
        "buy_sell": "buy",
        "date": "10/07/2018"
    }
    ,
    {
        "name": "y",
        "no": 10,
        "buy_sell": "sell",
        "date": "11/07/2018"
    }]

This has an undesired date format which is %d/%m/%Y whereas I would like it to be %Y-%m-%d.

What I have tried in order to change the format was to turn the dict into a pd.DataFrame and after that change the format of the column date (and then turn it again to a dict), here is what I tried:

tabla = pd.DataFrame(diction)
tabla['date'] = pd.to_datetime(tabla['date'])
tabla['date'] = tabla['date'].dt.strftime('%Y-%m-%d')

I don't know why it seems to be confusing the day with the month and is throwing out the output:

  buy_sell       date      name    no
0      buy    2018-10-07     x      10
1     sell    2018-11-07     y      10

My desired output would be:

  buy_sell       date      name    no
0      buy    2018-07-10     x      10
1     sell    2018-07-11     y      10

with the format %Y-%m-%d.

Upvotes: 0

Views: 44

Answers (2)

MJB
MJB

Reputation: 873

If all you want to do is to change the format of the dates in the dictionaries you could simply:

for d in diction:
    d['date'] = '{}-{}-{}'.format(d['date'][6:10], d['date'][3:5], d['date'][:2])

No need for pandas and converting data twice.

Upvotes: 1

fuglede
fuglede

Reputation: 18201

When you parse the dates, you could use

pd.to_datetime(df.date, dayfirst=True)

instead.

Upvotes: 0

Related Questions