2

I'm trying to print out data values extracted from excel file using pandas but the dates are coming with hours values as well

the code:

import pandas as pd

df = pd.read_excel(r'C:\gits\PCIv1.xlsm',sheet_name=9,names=None)

df = df.dropna()
print(df)

the output

  Unnamed: 0             Unnamed: 1           Unnamed: 2
0         ID                   Loja                 Data
6         19  B019 BOMPREÇO PIEDADE  2020-05-17 00:00:00

I want to eliminate the '00:00:00' and keep only the day/month in format DD/MM

Any help?

Tks

2
  • On the column with the date make sure the datatype is datetime and use something like df[“date”].str.apply(lambda x: x.strftime(“%d/%m”) Commented May 17, 2020 at 13:41
  • @JQadrad, this will cause value error since value in 0th index is not a valid date pattern. Commented May 17, 2020 at 14:00

2 Answers 2

2

Use converters while reading the excel which will make your life easier, then you have to apply dt.strftime

import pandas as pd
df2 = pd.read_excel('sample.xlsx', converters = {'Date' : pd.to_datetime})
df2['Date'] = df2['Date'].dt.strftime('%d/%m')
df2

Try the below code (Format the field after reading the excel)

df1 = pd.DataFrame({'Name':['A','B','A','B','C']
                    , 'ID':[3,4,3,5,6]
                    , 'Date':['2019-12-10 00:00:00','2019-12-10 00:00:00','2019-12-10 00:00:00'
                              ,'2019-12-10 00:00:00','2019-12-10 00:00:00']})
df1['Date'] = pd.to_datetime(df1['Date'], format="%Y-%m-%d %H:%M:%S", errors="coerce").dt.strftime('%d/%m')
df1

Then write your DataFrame into the Excel

Sign up to request clarification or add additional context in comments.

1 Comment

great! df['Data'] = df['Data'].dt.strftime('%d/%m') gave me a perfect solution! Tks!
0

Try this,

import pandas as pd

df = pd.read_excel(r'C:\gits\PCIv1.xlsm',sheet_name=9)
pd.to_datetime(df['Data'], format="%Y-%m-%d %H:%M:%S", errors="coerce").dt.strftime("%d-%m")

to_datetime

Comments

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.