. Advertisement .
..3..
. Advertisement .
..4..
Figuring out how to convert datetime to string in Pandas is a problem that any data scientist must face at least once. After all, it’s among the most vital backbones of our profession, serving as the basis for many advanced techniques.
For this reason, we believe you should master how to perform this conversion and prepare this guide.
Preparing The Data
Before we can start dissecting the problem, we must prepare something for the functions to work with.
In other words, we will create a data frame with some columns and rows. Then, we shall put the solutions to test and see if they can produce the results we want.
import pandas as pd
technologies = ({
'Courses':["Spark","PySpark","Hadoop"],
'Fee' :[22000,25000,23000],
'InsertedDate':["2021/11/24","2021/11/25","2021/11/26"]
})
df = pd.DataFrame(technologies)
# Use pandas.to_datetime() to change datetime format
df['DateTypeCol'] = pd.to_datetime(df.InsertedDate)
print(df)
Convert datetime To String In Pandas Using astype()
The first approach is to use astype()
to convert your datetime value into a string. Its main advantage is that it does not change the variable’s format. This approach is the fastest and most robust when your date has the correct format.
The result will be a string added into your data frame, replacing the datetime value present there before.
df['ConvertedDate']=df['DateTypeCol'].astype(str)
print(df)
As we mentioned, this method is among the most robust, as it doesn’t need to spend computing value on changing formats, etc. That is why it’s also capable of changing the datetime values into a string on multiple input columns.
Do not underestimate this strength, as it can make your life a lot easier, especially when there is a huge database to take care of. The only thing you need to do is ensure that every column’s name is included in a list, then feed that list to astype().
date_columns = ["date_col1","date_col2","date_col3"]
df[date_columns] = df[date_columns].astype(str)
Convert datetime To String In Pandas Using pandas.Series.dt.strftime()
Another method that a lot of people use is pandas.Series.dt.strftime()
. While it takes a bit more work than the second approach, this method has a clear advantage in that it allows you to make changes to the format.
For example, if your data frame has a datetime value with the YY/MM/DD format, this solution allows you to change it to DD/MM/YY, etc.
The function’s name, strftime, is the shortened form of string from time. In other words, it’s specifically built as an answer to this specific issue.
df['ConvertedDate'] = df['DateTypeCol'].dt.strftime('%m/%d/%Y')
print(df)
Convert datetime To String In Pandas Using DataFrame.style.format() And Lambda Function
If you want your string to have a specific mm/dd/yyyy
format, there is nothing better than using the DataFrame.style.format()
function alongside the Lambda Function.
df.style.format({"InsertedDate": lambda t: t.strftime("%m/%d/%Y")})
print(df)
DataFrame.style.format()
tells the computer that you want to reformat the input variable, while the lambda function tells it what you want to be done. However, a lot of newer users tend to mess up the syntax, as it’s on the more complicated side.
It does take a while to tell the difference between join() and merge(), much less a problem of this caliber.
Conclusion
After reading this article, you can be sure that the Convert datetime To String In Pandas problem will no longer plague you. All the approaches that we have provided have specific strengths and weaknesses. As long as you can make use of them in a proper way, they will be as robust as you need.
Leave a comment