Home > Mobile >  Is there a way to select all rows created today(current date), if that column has time format date a
Is there a way to select all rows created today(current date), if that column has time format date a

Time:01-18

If I have a table that contains:

table_id    id_from_other_table    date_time_when_this_row_was_added
[(1,        200,                   '2023-01-06 08-11-21')]
[(2,        200,                   '2023-01-07 07-21-21')]
[(3,        200,                   '2023-01-07 08-10-10')]

Can I get all the rows that were created at today's date which comes from:

today_date = datetime.datetime.now().strftime("%Y-%m-%d")

although the time format for values inside that columns are in this time format ? :

datetime.datetime.now().strftime("%Y-%m-%d %H-%M-%S")

I did the query like this:

id = 200
today_date = datetime.datetime.now().strftime("%Y-%m-%d")
query = 'SELECT * FROM table WHERE id = ? AND date_time_when_this_row_was_added LIKE ?%'
cursor.execute(query, (id, today_date)

But the returned list is empty. What I want is to get all rows created today if there are any and return the most recent row created today. I know how the get the most recent row created today, but I don't know hot to get all rows that were created today regardless the time.

I tried this query too and list returned is still empty:

id = 200
today_date = datetime.datetime.now().strftime("%Y-%m-%d")
query = 'SELECT * FROM table WHERE id = ? AND DATE(date_time_when_this_row_was_added) = DATE(?)'
cursor.execute(query, (id, today_date)

CodePudding user response:

In SQLite there is no datetime data type, so your datetimes are actually strings.

Although the format that you use to store the dates is not the proper ISO format YYYY-MM-DD hh:mm:ss, you can use the string function SUBSTR() to extract the date part of the datetimes and compare it to the current date which you can get with SQLite's function date(), so there is no need to use Python code to get the current date and pass it as a parameter to the query:

query = """
  SELECT * 
  FROM tablename 
  WHERE id = ? 
    AND SUBSTR(date_time_when_this_row_was_added, 1, 10) = date()
"""
cursor.execute(query, (id,))

or, if you want the current date in local time:

query = """
  SELECT * 
  FROM tablename 
  WHERE id = ? 
    AND SUBSTR(date_time_when_this_row_was_added, 1, 10) = date('now', 'localtime')
"""
cursor.execute(query, (id,))
  • Related