How can can I create a Teradata SQL Timestamp without milliseconds in a SELECT statement?
For instance, "2020-06-23 14:39:11".
The format should be "YYYY-MM-DDBHH:MI:SS".
In Teradata 16 you can use the code below.
Timestamp without milliseconds
SELECT Current_Timestamp(0) AS DATE_TIME;
Timestamp with milliseconds
SELECT Current_Timestamp AS DATE_TIME_MS;
Your question is a little unclear, but if you've got an existing field stored as timestamp(6) (with milliseconds), you can cast it as timestamp(0). It's kind of funky though, you can't just directly cast it. You have to cast it as a string, substring it to lose the millis, then you cast it back as timestamp(0).
cast (substring(cast(<ts_column> as varchar(26)) from 1 for 19) as timestamp(0))
Related
I've received a SQLite file with .db extension.
Opening it, I have a column with serial numbers: i.e. 1600414704594 (that should correspond to 2020-10-09 and whatsover time)
The db comes from outside and I don't know how that date field has been built.
Could you suggest me a query to get a valid date/time from that db column ?
I've tried reading this post but none of the given solution returned me a valid (and actual) date, please help me.
It looks like an Unix time in milliseconds. SQLite's unixepoch modifier expects it in seconds. The conversion is fairly easy :
SELECT DATETIME(1600414704594 / 1000, 'unixepoch')
2020-09-18 07:38:24
I cannot seem to figure out why datetime does not work for me on some data I imported from CSV. I have a column, TIMESTAMP, which is of type datetime.
Select TIMESTAMP from GPS limit 1 <-This gives me a time, "6/29/2009 00:00:00"
Select datetime(TIMESTAMP) from GPS limit 1 <- This gives me a pink field in SQLite manager, which seems empty.
Select datetime('now') from GPS limit 1 <- This gives me the current date and time. ("2012-12-19 20:45:17") It is formatted differently than my other data - is there a datatype issue?
What is going on? Did my "Timestamp" data not actually get converted into a DATETIME object? Why is it stored as text? Is there a way to fix this?
SQLite does not have a native date/time type; dates are stored either as numbers or as strings.
To be understood by SQLite's built-in date functions, date strings must have a format like yyyy-mm-dd hh:mm:ss.
I have a SQLite database where I store the dates as ticks. I am not using the default ISO8601 format. Let's say I have a table defined as follows:
CREATE TABLE TestDate (LastModifiedTime DATETIME)
Using SQL, I wish to insert the current date and time. If I execute any of the below statements, I end up getting the date and time stored as a string and not in ticks.
INSERT INTO TestDate (LastModifiedTime) VALUES(CURRENT_TIMESTAMP)
INSERT INTO TestDate (LastModifiedTime) VALUES(DateTime('now'))
I have looked at the SQLite documenation, but I do not seem to find any option to obtain the current timestamp in ticks.
I can of course define a parameter in C# and store the value as a System.DateTime. This does result in the datetime getting stored to the database in ticks.
What I would like to do is be able to insert and update the current timestamp directly from within the SQL statement. How would I do this?
Edit:
The reason I want the data stored as ticks in the database, is that the dates are stored in the same format as stored by the ADO.Net data provider, and so that when the data is also queried using the ADO.Net provider it is correctly retrieved as a System.DataTime .Net type.
This particular oddity of SQLite caused me much anguish.
Easy way - store and retrieve as regular timestamp
create table TestDate (
LastModifiedTime datetime
);
insert into TestDate (LastModifiedTime) values (datetime('now'));
select datetime(LastModifiedTime), strftime('%s.%f', LastModifiedTime) from TestDate;
Output: 2011-05-10 21:34:46|1305063286.46.000
Painful way - store and retrieve as a UNIX timestamp
You can use strftime to retrieve the value in ticks. Additionally, to store a UNIX timestamp (roughly equivalent to ticks), you can can surround the number of seconds in single-quotes.
insert into TestDate (LastModifiedTime) values ('1305061354');
SQLite will store this internally as some other value that is not a UNIX timestamp. On retrieval, you need to explicitly tell SQLite to retrieve it as a UNIX timestamp.
select datetime(LastModifiedTime, 'unixepoch') FROM TestDate;
To store the current date and time, use strftime('%s', 'now').
insert into TestDate (LastModifiedTime) VALUES (strftime('%s', 'now'));
Full example:
create table TestDate (
LastModifiedTime datetime
);
insert into TestDate (LastModifiedTime) values (strftime('%s', 'now'));
select datetime(LastModifiedTime, 'unixepoch') from TestDate;
When executed by sqlite3, this script with print:
2011-05-10 21:02:34 (or your current time)
After further study of the SQLite documentation and other information found on date number conversions, I have come up with the following formula, which appears to produce correct results:
INSERT INTO TestDate(LastModifiedTime)
VALUES(CAST((((JulianDay('now', 'localtime') - 2440587.5)*86400.0) + 62135596800) * 10000000 AS BIGINT))
Seems like a painful way to produce something that I would expect to be available as a built-in datetime format, especially that the database supports the storing of datetime values in ticks. Hopefully, this becomes useful for others too.
Update:
The above formula is not perfect when it comes to daylight savings. See section Caveats And Bugs in SQLite docs regarding local time calculation.
The following will return the number of milliseconds since the UNIX Epoch:
SELECT (strftime('%s', 'now') - strftime('%S', 'now') + strftime('%f', 'now')) * 1000 AS ticks
It works by grabbing the number of seconds since the Unix Epoch (%s), subtracting the number of seconds in the current time (%S), adding the number of seconds with decimal places (%f), and multiplying the result by 1000 to convert from seconds to milliseconds.
The subtraction and addition are to add precision to the value without skewing the result. As stated in the SQLite Documentation, all uses of 'now' within the same step will return the same value.
I have a textbox which displays the date as 01-May-2011 but the database coumis in format of datetime ... how to enter date in date time column of database. ..
how to wite the sqlquery for this ?
You can convert that format to a DateTime like this
string dateString = "01-May-2011";
string format = "dd-MMM-yyyy";
var result = DateTime.ParseExact(dateString, format, CultureInfo.InvariantCulture);
if you're using LINQ to SQL or even ADO with a parameter of type DateTime, the conversion to a format that SQL understands will be done automatically for you.
If you're building the SQL by concatenating a string manually (not recommended!) you should try to reconvert to a string in the format 'yyyyMMdddd' (corrected as per AdaTheDev's comment, notice the single quotes). Other formats may or may not be recognized by sql depending on the language settings on both your client and your SQL Server
SQL Server is pretty good about taking in datetime values. If you pass the date as a parameter you can put quotes around it ('01-May-2011') and ignore the time. The database will automatically fill in a default time so that you don't have to worry about it.
Pass field value as nvarchar to database and use following to cast it to datetime.
Declare #dt nvarchar(20)
SET #dt = '01-May-2011'
select cast(#dt as datetime)
One thing to be aware of is that dates w/o time will be interpreted as May 1 2011 12AM. IE, without a time specified, SQL Server will always set the time to midnight. So if you have just the date as a field and you want records from May 1, you can't do
WHERE datefield = '5/1/2011'
This will find records where the datefield is May 1st Midnight. You have to do
WHERE datefield >= '5/1/2011' and datefield < '5/2/2011'
This doesn't really pertain to your question, but I've seen it trip up a LOT of people. Myself included.
Just convert it to dateTime
DateTime _ConvertedDate = Convert.ToDateTime(txtDate.Text);
this converts into datetime
I am new to development and want to know the professional way to deal with dates in SQL Server. In my applications mainly we deal with the DATE datatype and no concern with time part. Also maintaining the format dd/mm/yyyy
So for example if I have the table with the following structure.
EmployeeTable
---------------
emp_id int
emp_name varchar(50)
join_date date
and if I want to query "join_date" in between start date and end date and pass the dd/mm/yyyy as stored procedure criteria and want to query.
What is the professional way to handle dates? I always convert date in varchar and then do the comparison which I guess is the unprofessional way of doing it. So please guide how to do it in procedure with example I would appreciate.
SQL handles dates just fine, so you do not need to convert the dates.
If you pass in the parameters as date types, then you will have no problem:
CREATE PROCEDURE myProc
#start date,
#end date
AS
SELECT emp_id, emp_name, join_date
FROM EmployeeTable
WHERE join_date BETWEEN start AND end;
Unless you want to format a date in your output in a specific way, there's no reason to convert the date to a varchar. You're using the date datatype, so let SQL do the comparisons for you.
If you want to compare dates in a date range, you can use this:
WHERE join_date BETWEEN '2010-01-01' AND '2010-12-31'
Keep dates as dates. Do not convert it to strings. That is unnecessary.
When you send dates in to SQL Server from your code, do it with parameters, then you don't have to worry about the right format in your strings.
SQL Server Date data types:
Date: 0001-01-01 through 9999-12-31
SmallDateTime: 1900-01-01 through
2079-06-06 (Accuracy 1 minute)
DateTime: January 1, 1753, through
December 31, 9999 (Accuracy
millisecond)
DateTime2: 0001-01-01 through
9999-12-31 (Accuracy 100 nanoseconds)
It's a minor point but worth noting that all queries presented to SQL Server are in TEXT. At some stage, based on some language and translation setting in the data access layer (OLEDB, Native, ADO) it gets turned into a textual form, so dates are always presented as "text".
The best format to use is always YYYYMMDD for SQL Server. Even YYYY-MM-DD can be wrong, for obscure dateformat settings. See this example.
set dateformat dmy -- more than common for non-US locations
select CONVERT(varchar, convert(datetime, '2010-12-31'), 112)
It fails.
Msg 242, Level 16, State 3, Line 3
The conversion of a varchar data type to a datetime data type resulted in an out-of-range value.
That covers the format to use when you have to construct the date embedded in the SQL statement. When possible however, please parameterize queries for benefits like
prevention of SQL injection
letting the db connectivity layer ensure the right formats when generating the TSQL
query plan re-use on the SQL Server
point 3 = better performing queries and more efficient SQL Server