How to change format of data to '%Y%m%d' in Pandas?
16,302
Solution 1
pd.to_datetime
is used to convert your series to datetime
:
s = pd.Series(['2018-01-31 00:00:00'])
s = pd.to_datetime(s)
print(s)
0 2018-01-31
dtype: datetime64[ns]
pd.Series.dt.strftime
converts your datetime
series to a string in your desired format:
s = s.dt.strftime('%Y%m%d')
print(s)
0 20180131
dtype: object
Solution 2
pd.to_datetime
will convert a string to a date. You want to covert a date to a string
df['mydate'].dt.strftime('%Y%m%d')
Note that it's possible your date is already a string, but in the wrong format in which case you might have to convert it to a date first:
pd.to_datetime(df['mydate'], format='%Y-%m-%d %H:%M:%S').dt.strftime('%Y%m%d')
Author by
Joe
Updated on June 14, 2022Comments
-
Joe almost 2 years
I have a DF with first column showing as e.g.
2018-01-31 00:00:00
.I want to convert whole column (or during printing / saving to other variable) that date to
20180131
format. NOT looking to do that during saving to a CSV file.Tried this but it did not work:
df['mydate'] = pd.to_datetime(df['mydate'], format='%Y%m%d')
-
Joe almost 6 yearsWhat is
.dt
? What libraries you are importing? -
Dan almost 6 yearsNo libraries, those are date functions built into pandas. Follow the link in the post.
-
Joe almost 6 yearsThis did not work for me:
AttributeError: 'Timestamp' object has no attribute 'dt'
-
Dan almost 6 yearswhat is
df['mydate'].dtype
? -
Dan almost 6 years@Joe Then
pd.to_datetime(df['mydate'], format='%Y-%m-%d %H:%M:S').dt.strftime('%Y%m%d')
will work. Certainly for your example date.