Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dropping time from datetime <[M8] in Pandas

So I have a 'Date' column in my data frame where the dates have the format like this

0    1998-08-26 04:00:00  

If I only want the Year month and day how do I drop the trivial hour?

like image 422
user2926266 Avatar asked Jul 16 '14 16:07

user2926266


People also ask

How do I remove the time from a date in python?

strftime() function to remove time from datetime in Python. We can also use the strftime() function to remove time from datetime in Python. The strftime() function is used to return a string based on a datetime object.


2 Answers

The quickest way is to use DatetimeIndex's normalize (you first need to make the column a DatetimeIndex):

In [11]: df = pd.DataFrame({"t": pd.date_range('2014-01-01', periods=5, freq='H')})  In [12]: df Out[12]:                     t 0 2014-01-01 00:00:00 1 2014-01-01 01:00:00 2 2014-01-01 02:00:00 3 2014-01-01 03:00:00 4 2014-01-01 04:00:00  In [13]: pd.DatetimeIndex(df.t).normalize() Out[13]: <class 'pandas.tseries.index.DatetimeIndex'> [2014-01-01, ..., 2014-01-01] Length: 5, Freq: None, Timezone: None  In [14]: df['date'] = pd.DatetimeIndex(df.t).normalize()  In [15]: df Out[15]:                     t       date 0 2014-01-01 00:00:00 2014-01-01 1 2014-01-01 01:00:00 2014-01-01 2 2014-01-01 02:00:00 2014-01-01 3 2014-01-01 03:00:00 2014-01-01 4 2014-01-01 04:00:00 2014-01-01 

DatetimeIndex also has some other useful attributes, e.g. .year, .month, .day.


From 0.15 they'll be a dt attribute, so you can access this (and other methods) with:

df.t.dt.normalize() # equivalent to pd.DatetimeIndex(df.t).normalize() 
like image 77
Andy Hayden Avatar answered Sep 20 '22 15:09

Andy Hayden


Another option

df['my_date_column'].dt.date 

Would give

0        2019-06-15 1        2019-06-15 2        2019-06-15 3        2019-06-15 4        2019-06-15 
like image 25
mccandar Avatar answered Sep 20 '22 15:09

mccandar