TAGS :Viewed: 11 - Published at: a few seconds ago

[ sqlite3 automatically insert date and hour after inserts ]

i have a table which holds some columns, ID(IntPK), Name(Text), Quantity(Int), Total(Int), Hour(Int),Date(Int)

I want to only have to insert a Name, a Quantity, and a Total, and then whenever a field is inserted into this table, i want it to automatically fill the hour and date with say, the hour and date from the computer.. Is there a way? I don't want to have to be typing the date and hour in everytime i insert a new field..

import sqlite3
conn = sqlite3.connect('Inventario.db')
c = conn.cursor()
conn.commit()

c.execute('''CREATE table if not exists sales(id INTEGER PRIMARY KEY, client TEXT, qty INTEGER, total INTEGER, hour INTEGER, date INTEGER)''')

Answer 1


You could create a method which detects a date using (for example) datetime.

import datetime
def insert_into_table(cursor,client,qty,total):
    date = datetime.datetime.now().date() # you can change it to your desired format as well as hour
    hour = datetime.datetime.now().hour()
    cursor.execute("INSERT INTO sales(client,qty,total,hour,date) VALUES (?,?,?,?,?)", (client,qty,total,hour,date))

Cursor could be an attribute of a class in my opinion so you don't need to add the attribute into the method.

EDIT: Thanks Jon Clements who helped me to improve my code to be more safe.