Friday afternoon and I'm fried. So fellow SQL aficionado's how to take the following WHERE clause in PostgreSQL and convert it to SQLite3 without using a compiled extension:
WHERE
DATE_TRUNC('day', c.start_date) <= DATE_TRUNC('day', q.date) AND
DATE_TRUNC('day', c.end_date) >= DATE_TRUNC('day', q.date)
going over the date/time functions in SQLite3 it seems like they're only for string formatting. Hope I'm seeing something wrong.
In PostgreSQL, DATE_TRUNC Function is used to truncate a timestamp type or interval type with specific and high level of precision. Syntax: date_trunc('datepart', field) The datepart argument in the above syntax is used to truncate one of the field,below listed field type: millennium. century.
The DATE_TRUNC function truncates a timestamp expression or literal based on the date part that you specify, such as hour, day, or month.
Let's start with the difference between DATEPART and DATETRUNC. DATEPART returns an INTEGER value; DATETRUNC returns a DATE. So, since we're in September, a DATEPART calculation at the 'month' level of detail will return 9. DATETRUNC will return 2018-09-01 12:00:00 AM - the first date of the 'month' argument.
Returns timestamp truncated to the unit specified in field .
SQLite has no data type for dates; it uses strings or numbers instead.
To remove the time portion of a timestamp, use the start of day
modifier.
The actual function to use (datetime()
, julianday()
, strftime('%s')
) depends on the format of your date values:
WHERE
datetime(c.start_date, 'start of day') <= datetime(q.date, 'start of date') AND
datetime(c.end_date, 'start of day') >= datetime(q.date, 'start of date')
In this case, you could just use the date()
function because you do not care about the actual format of the result, only how it compares:
WHERE
date(c.start_date) <= date(q.date) AND
date(c.end_date) >= date(q.date)
I couldn't make the above method work for hours or minutes.
For these, you can hack something up using the strftime
functionality like so:
select datetime(strftime('%Y-%m-%dT%H:00:00', 'now'));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With