-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMakeDBfromCSV.py
More file actions
72 lines (56 loc) · 2.07 KB
/
MakeDBfromCSV.py
File metadata and controls
72 lines (56 loc) · 2.07 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
import sqlite3
import csv
from datetime import datetime
csv_file = 'Canteens.csv'
"""
open SQLite database
"""
global conn
conn = sqlite3.connect('diners.db')
if(conn):
print ("Opened database successfully")
def splittimes(timestring):
#Split the timestring
time_open, time_closed = timestring.split('-')
# Strip trailing whitespace and convert to . to :
time_open = time_open.strip().replace('.', ':')
time_closed = time_closed.strip().replace('.', ':')
#Format to HH:MM
time_open_formatted = datetime.strptime(time_open, "%H:%M").strftime("%H:%M") # convert to datetime object and back to a string
time_closed_formatted = datetime.strptime(time_closed, "%H:%M").strftime("%H:%M")
#Error check
if time_open_formatted and time_closed_formatted:
return time_open_formatted, time_closed_formatted
else:
return None, None
def create_table():
#create a table
conn.execute('''CREATE TABLE CANTEEN(
ID INTEGER PRIMARY KEY,
NAME TEXT NOT NULL,
Location TEXT NOT NULL,
time_open TIME NOT NULL,
time_closed TIME NOT NULL);
''')
print ("Table created successfully")
def createRecords(namevar,locaitonvar,timeopenvar,timeclosedvar):
"""
create some records in the CANTEEN table
"""
conn.execute("INSERT INTO CANTEEN (Name, Location, time_open, time_closed) \
VALUES (?, ?, ?, ?)", (namevar, locaitonvar, timeopenvar, timeclosedvar));
conn.commit()
print ("Records created successfully")
#opendb()
create_table()
with open(csv_file, encoding='iso-8859-13', mode ='r')as csvfile:
reader = csv.DictReader(csvfile, delimiter=';')
# for row in reader:
# print(row)
for row in reader:
name = row['Name']
location = row['Location']
times = row['Open']
opent, closet = splittimes(times)
if(name and location and opent and closet):
createRecords(name,location,opent,closet) # send data to db