my data is formatted as such:
Username, Timestamp, Text
Joe Bloggs, Thu Oct 5 09:00:00 +0000 2017, Starting work
Jane Doe, Fri Oct 7 18:00:00 +0000 2017, Finished work
Tom Smith, Sat Oct 8 04:00:00 +0000 2017, Still coding this thing
I have a CSV of 5M rows like this, and I'd like to extract just those within 9am-5pm Mon-Fri.
I've read plenty of posts about dummy data and row-by-row extraction, but I'd like to actually filter the dataset as a whole and the examples are either incomplete or confusing to non-experts.
EDIT:
Thanks to @ivan7707 for the answer. Here is my completed code, I didn't include anything at the start as I knew my code was wildly wrong. (I was having issues with %z so resorted to splitting.)
import csv
from datetime import datetime
main_file = csv.DictReader(open("source.csv","rb"))
for row in main_file: #points to csv
username = row['Username']
text = row['Text']
timestamp = row['Timestamp']
#Convert timestamp to useable format
timestamp = timestamp.split()
timestamp = (timestamp[2] + "-" + timestamp[1] + "-" + timestamp[5] + " " + timestamp[3])
dt = datetime.strptime(timestamp, "%d-%b-%Y %H:%M:%S")
if dt.isoweekday() in range(1, 6): #If day is Mon-Fri
if dt.hour in range(9, 17): #If hour is 9am-5pm
output_file.writerow([username,text,timestamp]) #Save
EDIT 2:
Following the conversation ivan7707 and I had in the comments, here is the code that adds a week number to the data:
import csv
from datetime import datetime
main_file = csv.DictReader(open("source.csv","rb"))
for row in main_file:
username = row['Username']
text = row['Text']
timestamp = row['Timestamp']
#Convert timestamp to usable format as it was erroring with %z (+0000 part)
timestamp = timestamp.split()
timestamp = (timestamp[2] + "-" + timestamp[1] + "-" + timestamp[5] + " " + timestamp[3])
dt = datetime.strptime(timestamp, "%d-%b-%Y %H:%M:%S")
#Check if timestamp is within Mon-Fri 9am-5pm
if dt.isoweekday() in range(1, 6): #Mon-Fri
if dt.hour in range(9, 17): #9am-5pm
weekday_list.append(week)
output_file.writerow([username,text,timestamp,week]) #Writes to csv
#Handy bit to iterate one week per 5 business days
elif dt.isoweekday() == 7:
if len(weekday_list) > 1:
weekday_list = []
week += 1
Output for weekly script
Username, Timestamp, Text, Week,
Joe Bloggs, 06-10-2017 16:59:59, Hello World!, 1
Jane Doe, 09-10-2017 09:00:01, Hello!, 2