Reputation: 57
I am trying to extract all rows by date and time in a certain time frame (For example between 05/24/2021 12:50 and 07/24/2021 21:00. The data that I am using is shown below:
The code that I have now is:
import pandas as pd
df = pd.read_csv(r"C:\Users\OneDrive\Desktop\entries-88339.csv") #to read a CSV
print(df) #print original data
df.head()
df_rename = df.rename(columns = {'DATE': 'ENTRY DATE'}) #ENTRY DATE = DATE column
print(df_rename)
df_date = df_rename[(df_rename['ENTRY DATE'] <= '05-26-21') & (df_rename['ENTRY DATE'] > '05-03-21')] #date timeframe
print(df_date)
path = '/Users/Desktop' #for exporting to new csv
new_file = 'New_file.csv'
df_date.to_csv(new_file, index = False) #index = False is no index to csv
Upvotes: 1
Views: 1566
Reputation: 5918
Toy Example
Input Df
EntryDate Values
0 2021-05-21 16:31:00 1
1 2021-05-24 12:51:00 2
2 2021-06-21 16:31:00 3
3 2021-07-24 12:51:00 4
4 2021-07-24 22:31:00 5
Code
df.EntryDate = pd.to_datetime(df.EntryDate, format='%m/%d/%Y %H:%M')
start_date = '05-24-2021 12:50'
end_date = '07-24-2021 21:00'
mask = (df['EntryDate'] > start_date) & (df['EntryDate'] <= end_date)
df.loc[mask]
Output
EntryDate Values
1 2021-05-24 12:51:00 2
2 2021-06-21 16:31:00 3
3 2021-07-24 12:51:00 4
Upvotes: 1