Why is pandas not formatting dates with date_format
argument of to_csv
?
pandas.DataFrame([datetime.datetime.now().date()]).to_csv(date_format="%Y %b")
',0\n0,2025-07-31\n'
Pandas doesn't support date
- yet. Pandas was built on top of NumPy which only has a single 64-bit datetime type, datetime64[ns]
. date
values are stored as Object
s.
ser=pd.Series([date.today()])
print(ser.dtype)
-----
object
If you try to format the value, you get an error
ser.dt.strftime("%Y %b")
---
...
AttributeError: Can only use .dt accessor with datetimelike values. Did you mean: 'at'?
You need to parse the object
into a datetime first, then format it:
pd.to_datetime(ser).dt.strftime("%Y %b")
-----
0 2025 Jul
In the future Pandas will use Arrow as the backend, which does support dates. You can use it today as well if you specify the series type explicitly:
ser=pd.Series([date.today()],dtype="date32[pyarrow]")
ser.dt.strftime("%Y %b")
-----
0 2025 Jul
dtype: string[pyarrow]