Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
309 views
in Technique[技术] by (71.8m points)

python - removing time from date&time variable in pandas?

i have a variable consisting of 300k records with dates and the date look like
2015-02-21 12:08:51
from that date i want to remove time

type of date variable is pandas.core.series.series

This is the way i tried

from datetime import datetime,date
date_str = textdata['vfreceiveddate']  
format_string = "%Y-%m-%d"
then = datetime.strftime(date_str,format_string)   

some Random ERROR

In the above code textdata is my datasetname and vfreceived date is a variable consisting of dates
How can i write the code to remove the time from the datetime.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Assuming all your datetime strings are in a similar format then just convert them to datetime using to_datetime and then call the dt.date attribute to get just the date portion:

In [37]:

df = pd.DataFrame({'date':['2015-02-21 12:08:51']})
df
Out[37]:
                  date
0  2015-02-21 12:08:51
In [39]:

df['date'] = pd.to_datetime(df['date']).dt.date
df
Out[39]:
         date
0  2015-02-21

EDIT

If you just want to change the display and not the dtype then you can call dt.normalize:

In[10]:
df['date'] = pd.to_datetime(df['date']).dt.normalize()
df

Out[10]: 
        date
0 2015-02-21

You can see that the dtype remains as datetime:

In[11]:
df.dtypes

Out[11]: 
date    datetime64[ns]
dtype: object

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...