简体   繁体   中英

converting dataframe column from object to date not datetime

I am using python version 3.7.

I have a dataframe, df that contains one column called TDate.

The column looks like below.

 2019-01-01 00:00:00
 2019-01-02 00:00:00
 2019-01-03 00:00:00
 2019-01-04 00:00:00

When I do df.dtypes it tell me the column is of type object.

I then have the line below,

myDates = pd.to_datetime(df['TDate'])

So myDates is a pandas Series.

However if I access one element of this myDates series and check the type it tells me it is a libs.tslib.timestamps.Timestamp

I just want to convert the original dataframe column from an object to a date in the format yyyy-mm-dd. What is the best way of doing this?

I looked at converting a timestamp to a date but that didn't work as the timestamp is a string literal not a integer.

Use Series.dt.floor for remove time information from column (or better it is set to default 00:00:00 value in each datetime):

myDates = pd.to_datetime(df['TDate']).dt.floor('d')
#for save to same column
#df['TDate'] = pd.to_datetime(df['TDate']).dt.floor('d')

Or Series.dt.normalize :

myDates = pd.to_datetime(df['TDate']).dt.normalize()
#for save to same column
#df['TDate'] = pd.to_datetime(df['TDate']).dt.normalize()

If use:

myDates = pd.to_datetime(df['TDate']).dt.date

then output is python dates objects, so most datetimelike functions failed.

此代码段会将时间戳转换为日期

df['TDate']= pd.to_datetime(df['TDate']).dt.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