Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract time from datetime for comparison in pandas

I have a DataFrame

customer_number   purchase_time         quantity
14                2007-03-01 07:06:00   10
20                2007-03-12 13:05:00   13

I tried to find the total quantity bought in the morning and afternoon. I converted purchase_time into datetime

df['purchase_time'] = pd.to_datetime(df['purchase_time'])
# Baskets bought in morning.
df[df['purchase_time'] < '12:00:00']

However, the result is original dataset.

like image 597
Homesand Avatar asked Mar 17 '18 22:03

Homesand


People also ask

How do I compare timestamps in pandas?

Comparison between pandas timestamp objects is carried out using simple comparison operators: >, <,==,< = , >=. The difference can be calculated using a simple '–' operator. Given time can be converted to pandas timestamp using pandas. Timestamp() method.

Is pandas Timestamp the same as datetime?

Timestamp is the pandas equivalent of python's Datetime and is interchangeable with it in most cases. It's the type used for the entries that make up a DatetimeIndex, and other timeseries oriented data structures in pandas.

How do pandas handle time?

Using pandas datetime properties. Initially, the values in datetime are character strings and do not provide any datetime operations (e.g. extract the year, day of the week,…). By applying the to_datetime function, pandas interprets the strings and convert these to datetime (i.e. datetime64[ns, UTC] ) objects.


1 Answers

You can

df[df['purchase_time'].dt.time < pd.to_datetime('12:00:00').time()]
Out[152]: 
   customer_number       purchase_time  quantity
0               14 2007-03-01 07:06:00        10
like image 115
BENY Avatar answered Oct 24 '22 19:10

BENY