meine Daten als solche formatiert:Auswählen Workday Daten aus CSV-Python mit
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
Ich habe eine CSV 5 M Zeilen wie diese, und ich möchte nur jene innerhalb von 9.00 bis 05.00 Uhr Mo-Fr extrahieren .
Ich habe viele Beiträge über Dummy-Daten und Zeilen-für-Zeile-Extraktion gelesen, aber ich möchte tatsächlich den Datensatz als Ganzes zu filtern und die Beispiele sind für Nicht-Experten entweder unvollständig oder verwirrend.
EDIT:
Dank @ivan7707 für die Antwort. Hier ist mein vervollständigter Code, ich habe am Anfang nichts hinzugefügt, da ich wusste, dass mein Code völlig falsch war. (Ich hatte Probleme mit% z so zu einer Aufspaltung zurückgegriffen.)
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:
Nach dem Gespräch ivan7707 und ich in den Kommentaren hatte, hier ist der Code, der eine Woche Nummer hinzufügt zu den Daten:
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
Ausgang für wöchentliche Skript
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
Klingt gut. Warum schaffst du es nicht? Dann komm zurück, um mit einem bestimmten Problem, das du mit deinem Versuch hast, zu arbeiten, und wir helfen dir gerne. –
Danke für die Antwort. Ich habe das Problem dank ivan7707 unten gelöst, obwohl, wenn Sie wissen, wie man eine csv nach jeder Woche und Monat speichert, die wirklich hilfreich wäre. –