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.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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

Method 2

You’re calling datetime.datetime.strftime, which requires as its first argument a datetime.datetime instance, because it’s an unbound method; but you’re passing it a string instead of a datetime instance, whence the obvious error.

You can work purely at a string level if that’s the result you want; with the data you give as an example, date_str.split()[0] for example would be exactly the 2015-02-21 string you appear to require.

Or, you can use datetime, but then you need to parse the string first, not format it — hence, strptime, not strftime:

dt = datetime.strptime(date_str, '%Y-%m-%d %H:%M:%S')
date = dt.date()

if it’s a datetime.date object you want (but if all you want is the string form of the date, such an approach might be “overkill”:-).

Method 3

simply writing
pd.to_datetime('date') will remove the Hour min & sec


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x