简体   繁体   中英

Pandas Dataframe convert string to data without time

I have a Pandas Dataframe df:

a     date
1     2014-06-29 00:00:00

df.types return:

 a    object
 date object

I want convert column data to data without time but:

df['date']=df['date'].astype('datetime64[s]')

return:

a   date
1   2014-06-28 22:00:00

df.types return:

 a    object
 date datetime64[ns]

But value is wrong.

I'd have:

a     date
1     2014-06-29

or:

a     date
1     2014-06-29 00:00:00

I would start by putting your dates in pd.datetime:

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

Now, you can see that the time component is still there:

df.date.values

array(['2014-06-28T19:00:00.000000000-0500'], dtype='datetime64[ns]')

If you are ok having a date object again, you want:

df['date'] = [x.strftime("%y-%m-%d") for x in df.date]

Here would be ending with a datetime:

df['date'] = [x.date() for x in df.date]
df.date

datetime.date(2014, 6, 29)

Here you go. Just use this pattern:

df.to_datetime().date()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM