Joe
Joe

Reputation: 13151

How to change format of data to '%Y%m%d' in Pandas?

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')

Upvotes: 2

Views: 30115

Answers (3)

user21121796
user21121796

Reputation: 11

Convert the string column with 2018-01-31 00:00:00. to a datetime:

df['mydate'] = pd.to_datetime(df['mydate'])

#Get your preferred strings based on format:

df['mydate'].dt.strftime('%Y-%m-%d')
#Output: '2018-01-31'

df['mydate'].dt.strftime('%Y%m%d')
#output:'20180131'

Upvotes: 1

Dan
Dan

Reputation: 45762

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')

Upvotes: 4

jpp
jpp

Reputation: 164843

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

Upvotes: 6

Related Questions