Pandas Convert Date (Datetime) To String Format
We are given a column containing datetime values in a pandas DataFrame and our task is to convert these datetime objects into string format. This conversion is useful for visualizing data, exporting it to external applications, or performing string operations. For example, if we have this input:
a = {
'dt': pd.to_datetime(['2024-01-01', '2024-01-02', '2024-01-03']),
'x': [101, 201, 301],
'y': [909, 1809, 2709]
}
Then the output after conversion to strings might look like:
dt x y
0 01-01-2024 101 909
1 02-01-2024 201 1809
2 03-01-2024 301 2709
Using astype(str)
The astype(str) method converts the datetime column directly into strings. This approach is simple but does not allow formatting customization.
import pandas as pd
a = {
'dt': pd.to_datetime(['2024-01-01', '2024-01-02', '2024-01-03']),
'x': [101, 201, 301],
'y': [909, 1809, 2709]
}
df = pd.DataFrame(a)
print(type(df['dt'][0]))
df['dt'] = df['dt'].astype(str)
print(type(df['dt'][0]))
Output
<class 'pandas._libs.tslibs.timestamps.Timestamp'> <type 'str'>
Explanation:
- astype(str) changes the entire column dt from datetime to string type.
- type() checks the datatype before and after conversion.
Using strftime()
The strftime() method formats each datetime value into a string based on the format you specify.
import pandas as pd
a = {
'dt': pd.to_datetime(['2024-01-01', '2024-01-02', '2024-01-03']),
'x': [101, 201, 301],
'y': [909, 1809, 2709]
}
df = pd.DataFrame(a)
df['dt'] = df['dt'].dt.strftime('%d-%m-%Y')
print(df)
df.info()
Output:
dt x y
0 01-01-2024 101 909
1 02-01-2024 201 1809
2 03-01-2024 301 2709
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 3 entries, 0 to 2
Data columns (total 3 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 dt 3 non-null object
1 x 3 non-null int64
2 y 3 non-null int64
Explanation:
- strftime('%d-%m-%Y') converts each date to a custom string format.
- The dt accessor is used to apply string formatting on datetime columns.
Using apply() with lambda
You can convert datetime to string using the apply() function with a lambda expression. This offers flexibility to apply custom logic during conversion.
import pandas as pd
a = {
'dt': pd.to_datetime(['2024-01-01', '2024-01-02', '2024-01-03']),
'x': [101, 201, 301],
'y': [909, 1809, 2709]
}
df = pd.DataFrame(a)
df['dt'] = df['dt'].apply(lambda d: d.strftime('%B %d, %Y'))
print(df)
Output
dt x y 0 January 01, 2024 101 909 1 January 02, 2024 201 1809 2 January 03, 2024 301 2709
Explanation:
- .apply(lambda d: d.strftime(...)) allows full customization of the date format.
- You can use any valid format inside strftime — e.g., full month name with %B.