0
df1 = pd.DataFrame(
          columns=["A", "B", "C"], 
          data=[['2017-01-01',np.nan, "ok"], ['2017-02-01',8,"fine"], ['2017-03-01',100,np.nan]])
df1.to_excel('test.xlsx', index=False)

enter image description here

I have a dataframe that column is string. I want to export the df to excel and make column A the date type with the format DDMMMYYYY (i.e. instead of '2017-01-01' I need '01JAN2017').

I have tried two things that they don't work:

df1['A'] = pd.to_datetime(df1['A']).dt.strftime('%d%b%Y')

or

df1['A'] = pd.to_datetime(df1['A'], format="%d%b%Y")

How to do this?

1

3 Answers 3

2

i had a similar use case. i used pandas and arrow!

maybe something like this?

import pandas as pd
import numpy as np
import arrow

df1 = pd.DataFrame(
    columns=["A", "B", "C"],
    data=[
        ['2017-01-01',np.nan, "ok"],
        ['2017-02-01',8,"fine"],
        ['2017-03-01',100,np.nan]
    ]
)

df1['A'] = df1['A'].apply(
    lambda val: arrow.get(val).format("DDMMMYYYY").upper()
)

df1.to_excel('test.xlsx', index=False)
Sign up to request clarification or add additional context in comments.

Comments

0

In Excel, format column A as a custom format:

dd*mmm*yyyy

The stars should allow for no spaces or operators to appear between the dates elements.

Also, read this for another take on formatting.

Comments

-1

You can first parse it to datetime object and then convert it to required format

from datetime import datetime
df1['A'] = datetime.strptime(df1['A'], '%Y-%m-%d').strftime("%d%b%Y").upper()

2 Comments

Thanks Zohaib. I got this error message: "TypeError: strptime() argument 1 must be string, not Series". Any idea how to resolve this issue?
from your question, it seems that df1['A'] is your date string. So find the expression for your date str and pass this in place of df1['A']

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.