PSQL: Syntax error when passing set date variable into datetime - sql

I'm working server-side (using SSH) in psql, where I set variables using the '\set' command.
My concern is this: I have a query where I'm inserting a set string (date) into a datetime, but I get thrown a syntax error.
Simple example:
SELECT
network_no,
program_no,
national_datetime.
FROM
views
WHERE
national_datetime
between ':from_date 06:00:00'
and ':to_date 05:59:59'::timestamp + '1 day'::interval
Where 'from_date' and 'to_date' have been set accordingly:
\set from_date 2017-07-10
\set to_date 2017-07-16
I know normally with dates you're supposed to set three sets of apostrophes to read it in correctly (I never looked up the reason), but I'm feeding this date into a datetime, so I figured using no apostrophes would work, but I get thrown this error:
ERROR: invalid input syntax for type timestamp: ":from_date 06:00:00"
LINE 40: between ':from_date 06:00:00'
Normally in a bash script this would work since it just passes the literal string value, but in this case, whether I put no or one set of apostrophes around the date values it won't pass the value (I'm assuming because of the way PSQL handles set variables.
I know there's ways around this, but I'm looking for a reason why something like this would be happening, and whether there's a simple way to fix the "invalid input syntax"--whether it be through casting a variable, setting the variable differently, etc.
Many thanks in advance!

:from_date is a variable that is not a string.
Here is a way to do it:
date :from_date + time ' 06:00:00'
see doc at https://www.postgresql.org/docs/9.2/static/functions-datetime.html

Related

Convert date in snowflake to YYYYMM

Snowflake documentation says to use TO_DATE('2022-01-01', 'YYYYMM'), however, when running that I receive the error message:
"Error: too many arguments for function [TO_DATE("policy_effective_date", 'YYYYMM')] expected 1, got 2"
Any help is appreciated.
I was expecting to see 2022-01-01 turn into 202201. Even if I need to bring in DD that's fine too, I can just capture the LEFT 6 digits, but regardless the system is saying it's too many arguments.
TO_DATE() function accepts string/varchar format date and converts to Date Data type. For that we need to pass existing String date type format to parse. To Convert to the required format we need to use to_varchar as given in the documentation. https://docs.snowflake.com/en/sql-reference/functions-conversion.html

Conversion failed when converting date and/or time from character string when attributes and parameters are the same data type

I'm running a very simple query where I'm declaring an attribute (#BeginDate) and setting it to equal a report parameter (BeginDate). Both the attribute and the parameter have datetime data types
Report Parameters Setup
DECLARE
#BeginDate datetime
SET #BeginDate='BeginDate'
SELECT *
FROM MessageDeliveries AS MD
WHERE MD.ProcessStart >='BeginDate';
When I run the report I receive the following error message: Conversion failed when converting date and/or time from character string.
Any thoughts on how to correct this?
It's an SQL database. I figured out the solution to my issue. The:
SET #BeginDate='BeginDate'
clause was missing the ^. It should be:
SET #BeginDate='^BeginDate^'
When I made that change the query worked.

Regex or conversion for 'YYYY-MMM-DD'

I'm working with data in t-SQL and in order to automate my package in SSIS that will process each file with each given date, I need to figure out the regex or conversion for a file such as 'leads_2019-Dec-22' so the package can complete.
So far this is as far as I've gone, however this only works for 'YYYY-MM-DD' formats. I'm unable to change the format from the data loader tool I have, so there's no easy fix to this other.
#[User::UploadedFile] =
REPLACE(REPLACE(REPLACE(REPLACE(#[User::UploadedFileName], "yyyy",
(DT_STR,4,1252)DATEPART( "yyyy" , getdate())),"mm",RIGHT("0"+
(DT_STR,4,1252)DATEPART("mm",getdate()),2)), "dd", RIGHT("0"+
(DT_STR,4,1252)DATEPART("dd",getdate()),2)), "hh", right("0" +
(DT_STR,4,1252)DATEPART("Hh",getdate()),2) )
Has anyone dealt with this before and if so, how did/would you solve this using an Expression?
SQL Server does not support regular expressions.
However, the format used in the file name is very similar to a format you can use with convert to get the actual date from it's string representation.
The format convert supports under style 106 is dd mom yyyy - meaning all you have to do is isolate the date part from the string, replace the hyphens with spaces, and convert.
Please note that if the default language of the current login is not English, you might get errors because the month names depends on the language settings.
This is why I've included the set language statement in my code:
SET LANGUAGE us_english;
DECLARE #FileName varchar(20) = 'leads_2019-Dec-22';
SELECT CONVERT(Date, REPLACE(RIGHT(#FileName, 11), '-', ' '), 106);
Result:
2019-12-22
If you can be sure, now and forever, that this will never-ever run in systems with a different culture you can use easy conversions or set the language and culture for a session specifically.
But - if ever run on different systems - this might pass all your internal tests and may break in production with silly errors.
Culture specific approaches (and even worse: language specific ones) are very dangerous...
To overcome this you can use the following culture-safe approach (but it will be slower than simple conversions):
--Your question is not clear for me about the actual input.
--The string I use here seems to be your needed outcome...
--However, you will get the ghist how you can approach this issue with any given value...
DECLARE #TheFileName varchar(20) = 'leads_2019-Dec-22';
--not needed, just for testing... (in Germany "Dec" needs to be "Dez"...)
SET LANGUAGE GERMAN;
SELECT FORMAT(TRY_PARSE(RIGHT(#TheFileName,11) AS DATE USING 'en-us'),'yyyy-MMM-dd','en-us');
You have three obstacles:
First is to cut off the pure date. I do this by using RIGHT assuming we always need the rigth-most eleven characters.
Second is to get a date-typed value out of this. TRY_PARSE() accepts a culture parameter to ensure correct reading.
Third is to create the correct output. Here I use FORMAT(), which again allows for a specific culture.
Assuming you want the an output string in YYYY-MM-DD format from a variable called UploadedFileName that has data like 'leads_2019-Dec-22', you can just replace the "leads_" part and convert the rest to a date. Then you can parse the date to change it to the desired YYYY-MM-DD format:
(DT_WSTR, 4) YEAR((DT_DATE) REPLACE(#[User::UploadedFileName],"leads_","")) + "-" +
(DT_WSTR, 2) MONTH((DT_DATE) REPLACE(#[User::UploadedFileName],"leads_","")) + "-" +
(DT_WSTR, 2) DAY((DT_DATE) REPLACE(#[User::UploadedFileName],"leads_",""))

How to remove "+00:00" from end of datetime.datetime object. (not remove time)

I'm calling a database, and returning a datetime.datetime object as the 3rd item in a tuple.
The SQL statement is: SELECT name,name_text,time_received FROM {}.{} WHERE DATE(time_received)=CURRENT_DATE LIMIT 1
If I do print(mytuple[2]) it returns something like: 2017-05-31 17:21:19+00:00 but always with that "+00:00" at the end for every value. How do I remove that trailing "+00:00" from the datetime.datetime object?
I've tried different string-stripping methods like print(mytuple[2][:-6]) but it gives me an error saying that datetime.datetime object is not subscriptable. Thanks for any help!
Docs:
to_char(timestamp, 'YYYY-MM-DD HH24:MM:SS') would be one way.
For your specific case:
SELECT name,name_text,to_char(time_Received, 'YYYY-MM-DD HH24:MM:SS)'
Time received (mytuple[2]) would then be formatted as character data instead of time.
So if your program is handling it as a date, we'd have to convert it back to a date datatype
I imagine in order to use string stripping methods, you must first convert it to a string, then strip it, then convert back to whatever format you want to use. Cheers
I think this is what you want:
from time import strftime
strftime("%Y-%m-%d %H:%M:%S")

vb.net datetime.parseExact error message saying invalid format

Hi am trying to use the datetime.parse exact object in vb.net, but I keep getting an error saying invalid format. Here is my statement, could anyone tell me what I am doing wrong??
Dim TimeStart As Date
TimeStart = DateTime.ParseExact("2013.07.15-07:10:02", "yyyy.MM.dd-HH:MM:SS", System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat)
The error is because the seconds must be lower case. Also, you're asking for the month twice. I suspect this is the format string you need:
yyyy.MM.dd-HH:mm:ss
Just as an informational bit, the upper case 'H' means it's looking for 24-hour time, instead of 12-hour time. Lower-case 'h' would mean 12-hour time. Here is the reference for custom datetime format string rules:
http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx