How to produce a datetime string using a pandas dataframe?

I am trying to create a string for a document automation project that connects to a pandas dataframe and takes a date and produces it in this format: %A, %B %d, %Y (Friday, April 21, 2023).

My code I have used so far is:

import pandas as pd
from datetime import datetime

# testing data
trial_data = [["EXA001.701","4/21/2023"]]
trial_df = pd.DataFrame(trial_data, columns=["matterNo","trial_date"])
...

date = trial_df.loc[trial_df['matterNo']== matter_input, 'trial_date'].iloc[0]

dt_obj = datetime.strftime(date, "%m/%d/%Y")
dt_string = datetime.strptime(dt_obj, '%A, %B %d, %Y')
dt_string

However, it appears to have an error but from what I understood my dt_obj was supposed to convert the variable: date to a datetime object.

TypeError: descriptor 'strftime' for 'datetime.date' objects doesn't apply to a 'str' object

I also was able to convert it to a datetime object prior using pd.to_datetime but got an error when I tried to convert it to the %A, %B %d, %Y format.

Does anyone know how to remedy this issue? I would prefer to use pandas but would gladly hear out any other alternatives!

>Solution :

First, make sure your date column is in the correct datetime format. In case it is not, perform the conversion.

After converting the date column to a datetime format, you can use the strftime function to format it as per your desired format.
Try this:

import pandas as pd
from datetime import datetime

# Testing data
trial_data = [["EXA001.701", "4/21/2023"]]
trial_df = pd.DataFrame(trial_data, columns=["matterNo", "trial_date"])

# Convert the 'trial_date' column to datetime format
trial_df['trial_date'] = pd.to_datetime(trial_df['trial_date'])

date = trial_df.loc[trial_df['matterNo'] == matter_input, 'trial_date'].iloc[0]

# Format the date as a string in the desired format
formatted_date = date.strftime("%A, %B %d, %Y")

print(formatted_date)

Leave a Reply