简体   繁体   中英

How to covert the format of datetime object in pandas

I want to remove the 00:00:00 portion in the 'Date' field in my df

My df (named 'log') looks like this:

                    Date  btc_value   coin_value  type
29   2015-09-06 00:00:00   0.000000   188.204591   buy
30   2015-09-07 00:00:00   1.012830     0.000000  sell
79   2015-10-26 00:00:00   0.000000   419.679226   buy

After revealing the data was of 'object' type after performing long.dtypes I tried changing to a string using: log['Date'] = log['Date'].astype('str')

It remained an object, how can I remove the 00:00:00 portion

If your dates are are always going to have all zeros in the time position then by virtue of converting them using pd.to_datetime pandas will represent them the way you want to.

log.Date = pd.to_datetime(log.Date)

print(log)

         Date  btc_value  coin_value  type
29 2015-09-06    0.00000  188.204591   buy
30 2015-09-07    1.01283    0.000000  sell
79 2015-10-26    0.00000  419.679226   buy

However, if you wand to guarantee to always get just the date component and you are ok with it being a string... then

log.Date = pd.to_datetime(log.Date).dt.strftime('%Y-%m-%d')

print(log)

          Date  btc_value  coin_value  type
29  2015-09-06    0.00000  188.204591   buy
30  2015-09-07    1.01283    0.000000  sell
79  2015-10-26    0.00000  419.679226   buy

Side note: dtype of object is what pandas uses for series of strings

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