How can I convert timestamps to dates in SQLite? - sqlite

How can I convert timestamps to dates in SQLite?
The following code only produces a Timestamp column and a Date columns with NULL values. The the SQL code needs to convert from a "08/28/2020 8:00" format.
SQL CODE:
'''Select Timestamp, strftime('%m-%d-%Y', Timestamp) as Date
FROM Room_Data'''
The SQLite documentation is pretty clear, but I can't seem to get the desired result.

The strftime is meant to format a date, rather than perform conversion.
In the meantime you could try something like that to gather the pieces:
SELECT Timestamp,
SUBSTR(c,7,4) || '-' || SUBSTR(Timestamp,1,2) || '-' || SUBSTR(Timestamp,4,2) as Date
FROM Room_Data
Since SQlite doesn't really have the concept of a date, unlike other DBMS, the best choice would be to convert your dates to integer, either as Unix timestamps or in string form (YYYY-MM-DD) but storing dates as integer like 20201010 would be acceptable too.
NB: be careful with names like Timestamp or Date, they are reserved keywords in many programming languages and DBMSes.

The original code won't work in Windows 10 for some reason. Trying this from a Linux distro (Kubuntu, in this case) seems to resolve the issue. In Windows, the date needs to be converted to a '2020-01-01' format to actually work.
SQLite is amazing, but not sure why functionality changes for Windows 10. Feel free to comment if you know more about the differences.

Related

SQLite date split

In SQLite, I have a 'date' field that's varchar(20), as an example dates currently read '12-AUG-15'. I need to split the date field into 4 separate fields: 'day', 'month', 'year', and 'month_num'. Problem is I don't know how to convert month names into numbers as well as the year into a 4 digit year. I'm thinking of using case and string concatenation functions? Any advice how to start it is well appreciated.
SQLite has very limited date and string functions. The date functions understand ISO 8601. You're better off in the long run converting to ISO 8601 and then using the date functions. It will sort better, and most everything understands ISO 8601 format.
SQLite doesn't have an easy way to do this, but you can write a user defined function to do the conversion. Most SQLite drivers allow you to write it in whatever language you're using. Here's an example in Ruby.
require "sqlite3"
require "date"
# Open a database
db = SQLite3::Database.new "test.db"
# Create a SQLite function date_to_iso()
db.create_function( "date_to_iso", 1 ) do |proxy, date|
# Convert 12-AUG-15 to 2015-08-12 (ISO 8601 format)
iso = Date.strptime(date, "%d-%b-%y");
# This is how you return the result via a FunctionProxy
proxy.result = iso.to_s
end
# Now you can use date_iso_iso() in SQLite queries in this process.
db.execute("UPDATE stuff SET date = date_to_iso(date)")
Then you can use strftime to query the individual date parts.
select
strftime("%d", date) as day,
strftime("%m", month) as month,
strftime("%Y", year) as year
from whatever;
Unfortunately, SQLite doesn't have a way to convert to the month name. You could write a big CASE statement.
select case strftime("%m", month)
when 1 then 'JAN'
when 2 then 'FEB'
...
end
from whatever;
Or you could add another user defined function to do the conversion.
But since you now have a standard date format, it's probably better to just return the whole ISO 8601 date and let the application do what it wants with it.

Where do I find the reference for TO_DATE format string

I need to convert a string formatted as MM/DD/YYYY HH:MI plus AM/PM, but can't find a complete reference to the format string to find how to specify the AM/PM part.
I would certainly appreciate information on how to do this, but would appreciate a link to a good source of documentation for this even more.
:EDIT
SELECT top 1
v.CalendarDateTime
,TO_TIMESTAMP(v.CalendarDateTime,'MM/DD/YYYY HH:MIAM') as CalendarDateTimeTS
--,CAST(TO_TIMESTAMP(v.CalendarDateTime,'MM/DD/YYYY HH:MIAM') AS TIMESTAMP(0) FORMAT 'MM/DD/YYYYBHH:MIBT') AS CalendarDateTimeTS2
12/03/2015 03:00AM 12/3/2015 03:00:00.000000
The commented out line produces a "DateTime field overflow" error.
You probably want TO_TIMESTAMP instead of TO_DATE.
The only bad thing about the Oracle function is the resulting datatype of TIMESTAMP(6) which can't be changed:
TO_TIMESTAMP('12/03/2015 03:00AM', 'MM/DD/YYYY HH:MIAM')
Using Teradata's FORMAT you can specify the timestamp precision, but it's less flexible than Oracle's, the string must match the format exactly:
CAST('12/03/2015 03:00AM' AS TIMESTAMP(0) FORMAT 'MM/DD/YYYYbHH:MIT')
On the Teradata site you'll find the (slow) online docu, e.g. TO_DATE formats or Teradata FORMATs. Of course you should download the full documentation CD for your release.
Please tell us at least which programming language are you using.
Normally it would be something like "MM/DD/YYYY HH:MI a" but we need to know first you language.

How to convert the format of inserted datetime in Informix?

I insert my date/time data into a CHAR column in the format: '6/4/2015 2:08:00 PM'.
I want that this should get automatically converted to format:
'2015-06-04 14:08:00' so that it can be used in a query because the format of DATETIME is YYYY-MM-DD hh:mm:ss.fffff.
How to convert it?
Given that you've stored the data in a string format (CHAR or VARCHAR), you have to decide how to make it work as a DATETIME YEAR TO SECOND value. For computational efficiency, and for storage efficiency, it would be better to store the value as a DATETIME YEAR TO SECOND value, converting it on input and (if necessary) reconverting on output. However, if you will frequently display the value without doing computations (including comparisons or sorting) it, then maybe a rococo locale-dependent string notation is OK.
The key function for converting the string to a DATETIME value is TO_DATE. You also need to look at the TO_CHAR function because that documents the format codes that you need to use, and because you'll use that to convert a DATETIME value to your original format.
Assuming the column name is time_string, then you need to use:
TO_DATE(time_string, '%m/%d/%Y %I:%M %x') -- What goes in place of x?
to convert to a DATETIME YEAR TO SECOND — or maybe DATETIME YEAR TO MINUTE — value (which will be further manipulated as if by EXTEND as necessary).
I would personally almost certainly convert the database column to DATETIME YEAR TO SECOND and, when necessary, convert to the string format on output with TO_CHAR. The column name would now be time_value (for sake of concreteness):
TO_CHAR(time_value, '%m/%d/%Y %I:%M %x') -- What goes in place of x?
The manual pages referenced do not immediately lead to a complete specification of the format strings. I think a relevant reference is GL_DATETIME environment variable, but finding that requires more knowledge of the arcana of the Informix product set than is desirable (it is not the first thing that should spring to anyone's mind — not even mine!). If that's correct (it probably is), then one of %p and %r should be used in place of %x in my examples. I have to get Informix (re)configured on my machine to be able to test it.

Does sqlite3 has analogue MySQL's CONVERT_TZ function?

I get exception when try to use CONVERT_TZ in RoR project:
SQLite3::SQLException: no such function: CONVERT_TZ
Is there some function in sqlite for convert timezone in a query?
To convert from UTC+0 to UTC+3:
SELECT datetime(columnName, '+3 hour') || '+03:00' AS myDate FROM tableName;
Explanation:
datetime(columnName, '+3 hour')
Above does the translation of hours, it simply tells SQLite to add 3 hours to the initial date. This would not be enough, because it only modifies date, without really telling that the timezone has changed, so we can do it manually, by appending '+03:00' to the final date string.
It makes the following conversion from 2015-03-05 15:03:43 to 2015-03-05 18:03:43+03:00
That means that the date format will change from YYYY-MM-DD HH:MM:SS to YYYY-MM-DD HH:MM:SS[+/-]HH:MM, which is a correct datetime format for SQLite, according to its documentation.
Read SQLite's documentation about date functions for any details, or just ask in comments and I can try to help even further. I don't want to paste the entire documentation page here.

SELECT clause with a DATETIME column in Sybase 15

I'm trying to do a query like this on a table with a DATETIME column.
SELECT * FROM table WHERE the_date =
2011-03-06T15:53:34.890-05:00
I have the following as an string input from an external source:
2011-03-06T15:53:34.890-05:00
I need to perform a query on my database table and extract the row which contains this same date. In my database it gets stored as a DATETIME and looks like the following:
2011-03-06 15:53:34.89
I can probably manipulate the outside input slightly ( like strip off the -5:00 ). But I can't figure out how to do a simple select with the datetime column.
I found the convert function, and style 123 seems to match my needs but I can't get it to work. Here is the link to reference about style 123
http://infocenter.sybase.com/help/index.jsp?topic=/com.sybase.help.ase_15.0.blocks/html/blocks/blocks125.htm
I think that convert's slightly wrongly documented in that version of the docs.
Because this format always has century I think you only need use 23. Normally the 100 range for convert adds the century to the year format.
That format only goes down to seconds what's more.
If you want more you'll need to past together 2 x converts. That is, past a ymd part onto a convert(varchar, datetime-column, 14) and compare with your trimmed string. milliseconds comparison is likely to be a problem depending on where you got your big time string though because the Sybase binary stored form has a granularity of 300ms I think, so if your source string is from somewhere else it's not likely to compare. In other words - strip the milliseconds and compare as strings.
So maybe:
SELECT * FROM table WHERE convert(varchar,the_date,23) =
'2011-03-06T15:53:34'
But the convert on the column would prevent the use of an index, if that's a problem.
If you compare as datetimes then the convert is on the rhs - but you have to know what your milliseconds are in the_date. Then an index can be used.

Resources