Python SQLite - Working with Date and DateTime - GeeksforGeeks

20 Sep, 2021
SQLite does not support built-in DateTime storage a class, but SQLite allows us to work with timestamp types. We can store and retrieve Python date and datetime information stored in the SQLite database tables by converting them to Python date and datetime types and vice-versa.
While inserting the datetime value, the python sqlite3 module converts the datetime into the string format. And when retrieving datetime values from SQLite tables, the sqlite3 module converts them into a string object. But we don’t want string type. We want the datetime to get stored in DateTime type. For that, we need to use detect_types as it takes PARSE_DECLTYPES and PARSE_COLNAMES as arguments in the connect method of the sqlite3 module.
Syntax: connect(‘DATABASE NAME’,detect_types=sqlite3.PARSE_DECLTYPES | sqlite3.PARSE_COLNAMES)
sqlite3.PARSE_DECLTYPES: The sqlite3 module parses the declared type for each column it returns then uses the type converters dictionary to execute the converter function registered for that type there.
sqlite3.PARSE_COLNAMES: The SQLite interface parses the column name for each column it returns. It will use the converters dictionary and then use the converter function found there to return the value.
First, we need to import the datetime module and to get the current time and date information now() function can be used. Then they store the datetime information in a variable, so it can be used to insert datetime in the SQLite table. To store the datetime information in the table, we need to use the column datatype as ‘TIMESTAMP’.
column_name TIMESTAMP
Below code creates a database ‘StudentAssignment.db’ and a table ‘ASSIGNMENT’. The code also inserts the data into the table with datetime information.
Python3
import datetimeimport sqlite3 # get the current datetime and store it in a variablecurrentDateTime = datetime.datetime.now() # make the database connection with detect_typesconnection = sqlite3.connect('StudentAssignment.db',                             detect_types=sqlite3.PARSE_DECLTYPES |                             sqlite3.PARSE_COLNAMES)cursor = connection.cursor() # create table in databasecreateTable = '''CREATE TABLE ASSIGNMENT (    StudentId INTEGER,    StudentName VARCHAR(100),    SubmissionDate TIMESTAMP);'''cursor.execute(createTable) # create query to insert the datainsertQuery = """INSERT INTO ASSIGNMENT    VALUES (?, ?, ?);""" # insert the data into tablecursor.execute(insertQuery, (1, "Virat Kohli",                             currentDateTime))cursor.execute(insertQuery, (2, "Rohit Pathak",                             currentDateTime))print("Data Inserted Successfully !") # commit the changes,# close the cursor and database connectionconnection.commit()cursor.close()connection.close()
 
 
Output:
 
Data Inserted Successfully !
 
In order to retrieve the stored datetime information from database tables, we can simply use the select query and can access the individual rows data. Here for retrieval of data and to check the datatypes in which the data is stored, we need to use the detect_types as arguments in the connect method of the sqlite3 module.
 
The below code retrieves the stored record from the ‘ASSIGNMENT’ table. The record contains the ‘datetime’ type information. 
 
Python3
import datetimeimport sqlite3 # make a database connection and cursor objectconnection = sqlite3.connect('StudentAssignment.db',                             detect_types=sqlite3.PARSE_DECLTYPES |                             sqlite3.PARSE_COLNAMES)cursor = connection.cursor() # select query to retrieve datacursor.execute("SELECT * from ASSIGNMENT where StudentId = 2")fetchedData = cursor.fetchall() # to access specific fetched datafor row in fetchedData:    StudentID = row[0]    StudentName = row[1]    SubmissionDate = row[2]    print(StudentName, ", ID -",          StudentID, "Submitted Assignments")    print("Date and Time : ",          SubmissionDate)    print("Submission date type is",          type(SubmissionDate)) # commit the changes,# close the cursor and database connectioncursor.close()connection.close()
Output:
As we can see in the output when we retrieve the submission data of students from ‘ASSIGNMENT’ table. We accessed each row of the table and printed them in a specific message. First-line contains the student name and the ID, on the second line we printed the datetime on which the student submitted the assignment, and on the third line we printed the type of the stored data, which is the type of datetime we stored in the table i.e., ‘datetime.datetime’. 
anikaseth98
Picked
Python-SQLite
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Defaultdict in Python
Create a directory in Python
Python | os.path.join() method
Python | Pandas dataframe.groupby()
Python | Get unique values from a list