Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Dates with RSQLite

Tags:

r

How do you write a SQL query with a date using RSQLite. Here is an example below. The dbGetQuery does not return any rows.

require(RSQLite)
require(ggplot2)
data(presidential)
m <- dbDriver("SQLite")
tmpfile <- tempfile('presidential', fileext='.db')
conn <- dbConnect(m, dbname=tmpfile)
dbWriteTable(conn, "presidential", presidential)
dbGetQuery(conn, "SELECT * FROM presidential WHERE Date(start) >= Date('1980-01-01')")
like image 715
jbryer Avatar asked Nov 19 '12 20:11

jbryer


People also ask

Does SQLite support date?

SQLite does not support built-in date and/or time storage class. Instead, it leverages some built-in date and time functions to use other storage classes such as TEXT , REAL , or INTEGER for storing the date and time values.

How does SQLite handle dates?

The date() function returns the date as text in this format: YYYY-MM-DD. The time() function returns the time as text in this format: HH:MM:SS. The datetime() function returns the date and time as text in their same formats: YYYY-MM-DD HH:MM:SS.

How do I insert the current date and time in SQLite?

Inserting Date and DateTime data 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.

How do I change the date format in SQLite?

Use the STRFTIME() function to format date\time\datetime data in SQLite. This function takes two arguments. The first argument is a format string containing the date/time part pattern. In our example, we use the format string '%d/%m/%Y, %H:%M'.


2 Answers

Just to illustrate, this works fine:

tmpfile <- tempfile('presidential', fileext='.db')
conn <- dbConnect(m, dbname=tmpfile)
p <- presidential
p$start <- as.character(p$start)
p$end <- as.character(p$end)

dbWriteTable(conn, "presidential", p)
dbGetQuery(conn, "SELECT * FROM presidential WHERE start >= '1980-01-01'")

You can read about the lack of native date types in SQLite in the docs here. I've been using strings as dates for so long in SQLite that I'd actually forgotten about the issue completely.

And yes, I've written a small R function that converts any Date column in a data frame to character. For simple comparisons, keeping them in YYYY-MM-DD is enough, and if I need to do arithmetic I convert them after the fact in R.

like image 56
joran Avatar answered Oct 19 '22 15:10

joran


Following on from @joran's answer, here's a simple function to convert date columns to string for a data.frame.

mutate(df, across(where(is.Date), ~ format(.x, "%Y.%m.%d")))
like image 21
Richard Knight Avatar answered Oct 19 '22 17:10

Richard Knight