Why Datetime Macro Variable wont convert to Character - datetime

All,
I am trying to nest a macro within a macro but am unsuccessful. The Start_Cycle variable is set every few months and updated manually. I want to create a start_point variable that goes back 6 months and I successfully created it, however, the output includes a space after the %STR as seen below
%let start_cycle = '01JUL2022:00:00:00'dt; /set to beginning month of this cycle/
%let start_point = %STR(%')%sysfunc(intnx(DTMONTH,&start_cycle.,-6,b),datetime19.)%STR(%')dt;
%put &start_point;
Output below
%let start_cycle = '01JUL2022:00:00:00'dt; /set to beginning month of this cycle/
%let start_point =
%STR(%')%sysfunc(intnx(DTMONTH,&start_cycle.,-6,b),datetime19.)%STR(%')dt;
%put &start_point; ' 01JAN2022:00:00:00'dt
^^Does anyone know why there is a space after the single quote? ' 01JAN2022:00:00:00'dt
Since it runs without issues, I decided to create another macro variable that does the same thing, but instead, the output needs to be converted to a character string in this format below (current Macro)
%let start_pointSales = '2022/01';
I tried multiple times using different ways of going about this, spent many hours looking through forum from SAS Communities to StackOverflow and even SAS youtube videos to no luck. Anyone have any luck in combating this?
To-Be Macro:
%let NEW_start_pointSales = %sysfunc(intnx(month,&start_cycle.,-6,b),yymms.);
%put &NEW_start_pointSales;
The NEW_start_pointSales will be used in the WHERE clause with Data type Varchar (21) using PROC SQL.
left join EDWSALE.DSCOE_LLD (where=( &NEW_start_pointSales. <= SALES_MONTH < &end_pointSales.
Output Error below:
NOTE: Writing TAGSETS.SASREPORT13(EGSR) Body file: EGSR
24
25 GOPTIONS ACCESSIBLE;
WARNING: An argument to the function INTNX referenced by the %SYSFUNC or %QSYSFUNC macro function is out of range.
NOTE: Mathematical operations could not be performed during %SYSFUNC function execution. The result of the operations have been set
to a missing value.
Any help is appreciated!

You cannot apply a format, YYMMS, designed to work on DAYS to a value that is in SECONDS. If you want to use a date format on a datetime value you need to convert the value from seconds to days. You could use the DATEPART() function or just divide by the number of seconds in a day.
Why are you trying to compare a variable that is CHARACTER to numbers? If you generate a macro variable with a string like 2022/01 and then use it to generate code like:
&NEW_start_pointSales. <= SALES_MONTH
that will result in code like:
2022/01 <= SALES_MONTH
which is comparing the number 2022 (any number divided by 1 is itself) to the value SALES_MONTH, which you just said was a character string.
What types of strings does SALES_MONTH contain? That will determine how (or whether) you can make inequality tests against it.
PS There is space in the output of DATETIME19 because that is how that particular format works. Note that there is a bug in the DATETIME format and you cannot use DATETIME18. to produce a string with four digits for the year even though only 18 characters would be used. The extra space does not matter to using the string in a datetime literal as the DATETIME informat will recognize the string even with the extra space.

Related

USQL reading last n days when file name pattern does not have day part

In data lake I have file names with pattern yyyyMM_data.csv. Now I want to read previous 3 days data. I am using below code -
DECLARE #ReportDate DateTime= DateTime.Parse("05/08/2017");
DECLARE #FeatureSummaryInput string=#"/FolderPath/{InputFileDate:yyyy}{InputFileDate:MM}_data.csv";
#FeaturedUsed =
EXTRACT Id string,InputFileDate DateTime
FROM #FeatureSummaryInput
USING Extractors.Csv(silent : true, skipFirstNRows : 1);
#FeaturedUsed=
SELECT *
FROM #FeaturedUsed
WHERE InputFileDate BETWEEN #ReportDate.AddDays(-3) AND #ReportDate;
If I run above code it runs with empty input. Please let me know if I am missing something. Why it is not reading correct file?
It seems like we need to must have "day" in file name pattern to work this.
Possibly I am missing something but, as you cast InputFileDate to DateTime it defaults to the first of the month, as no day is specified. For your test ReportDate set to 05/08/2017, your WHERE clause basically evaluates to Between 2017-08-02 And 2017-08-05, which will never be true.
Where do you expect the day element to come in with your files structured as yyyyMM?

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.

SAS Macro to R %sysfunc

I am currently working on converting a SAS script to R. As I am relatively new to SAS, I am having a hard time understanding the following statement -
VARS=date id sales units
/* create lag event variable names to be used in the RETAIN statement */
%let vars_l = lag_%sysfunc(tranwrd(&vars,%str( ),%str( lag_)));
Here, date, id etc. are all variables present in my current data set. I understand the function tranwrd is used to replace a value by another value in a Character variable. In this case, it creates new items as -
vars_l = lag_date lag_id lag_sales lag_units
Am I right? What is vars_l? Is it a list? Or are these variables that are added to my dataset?
Also what is the use of lag before %sysfunc in the code below for?
%let vars_l = lag_%sysfunc(tranwrd(&vars,%str( ),%str( lag_)));
Are lagged variables created at all or just variables with no values prefixed with lag_ is created?
I don't have access to SAS or the datasets to try and check the result. Any help on this would be great. Thanks!
The following code is basically creating macro variables to hold a list of variables to process. (Note: macros in SAS are mere text replacements!)
%let VARS=date id sales units ;
/* create lag event variable names to be used in the RETAIN statement */
%let vars_l = lag_%sysfunc(tranwrd(&vars,%str( ),%str( lag_)));
If you run the following code (to see what exactly is stored in VARS & vars_l macros you see the following in the log:
31 %put VARS::&VARS.;
SYMBOLGEN: Macro variable VARS resolves to date id sales units
VARS::date id sales units
32 %put VARS_l::&VARS_L.;
SYMBOLGEN: Macro variable VARS_L resolves to lag_date lag_id lag_sales lag_units
VARS_l::lag_date lag_id lag_sales lag_units
In R the equvialent would be the following:
VARS<-c("date", "id", "sales", "units" )
vars_l<-paste("lag_",VARS, sep="")
The second vars_l macro assignment is just adding lag_ to the begining of each space delimited value in VARS macro variable. Since the first value does not begin with a space, if you omit the lag_ at the begining of %let vars_l = lag_%sysfunc(tranwrd(&vars,%str( ),%str( lag_))); you will get the following stored in vars_l: date lag_id lag_sales lag_units
From the code I can see there are no variables created just yet, but you should find a data step later on which does that. The mention of RETAIN statement in the comments suggests just that.

SAS 9.3 DATETIME VARIABLE FORMAT AS DATE

I have a datetime22.3 variable which I would like to display as date.
for eg I want to display 17JUL2006:00:00:00.000 as 07/17/2006
How do I do this?
Thanks.
additional info:
Thanks for all the replies.
Actually, I tried to output it in the date format within proc sql. The output is being printed as ********** (stars). I am not sure what is going on.
I am trying to use INTCK in the following manner but get error. I am not sure what I am doing wrong. I would appreciate your help. Thanks.
PROC FORMAT;
PICTURE DTFMT LOW-HIGH='%0m/%0d/%Y' (DATATYPE=DATETIME);
RUN;
data want;
dt_val1='17JUL2006:00:00:00.000'dt;
dt_val2='17AUG2012:00:00:00.000'dt;
format dt_val1 dt_val2 dt_val3 dtfmt.;
dt_val3=intck('MONTH',dt_val1,dt_val2);
put dt_val3;
run;
You can't apply a standard date format directly against a datetime value, although there are some date formats you can prefix with 'DT' which will display a datetime as a date. Unfortunately the MMDDYY format is not one of these, however you could use DTDATE9. which would format your datetime as '17JUL2006'.
Another option is create your own format using the PICTURE statement, the example below will display the datetime as required.
proc format;
picture dtfmt low-high='%0m/%0d/%Y' (datatype=datetime);
run;
data want;
dt_val='17JUL2006:00:00:00.000'dt;
format dt_val dtfmt.;
run;
put(datepart(datetimevariable),yymmdd10.)
use the same princpiple in a data step
data _null_;
a='17JUL2006:00:00:00.000'd;
put a;
put 'formatted date='a MMDDYY10.;
run;
This is the output from my SAS 9.3
44 data _null_;
45 a = '17JUL2006:00:00:00:000'D;
46 put a;
47 put 'formatted ' a MMDDYY10.;
48 run;
16999
formatted 07/17/2006
NOTE: DATA statement used (Total process time):
real time 0.00 seconds
cpu time 0.00 seconds
Formatting dates in SAS can be tricky. One method I've used in a macro is this:
/* get the date time */
%let start_date=%sysfunc(datetime().,10);
/* use the DATETIME informat to format the date */
%let fmt_start_date=%sysfunc(putn(&start_date, DATETIME.));
/* format the datetime as a date */
%put "&fmt_start_date."d;
There's a bunch of different ways to format dates. You could also use the FORMAT statement if you're in a data step:
FORMAT STARTDATE YYMMDD10.;
In this case, the format of the column in the data step would give you YYYY-MM-DD and then you can separate the values and reconstruct from there.
There's additional information about SAS informats for dates here:
http://support.sas.com/documentation/cdl/en/etsug/60372/HTML/default/viewer.htm#etsug_intervals_sect008.htm
And here:
http://support.sas.com/documentation/cdl/en/etsug/63348/HTML/default/viewer.htm#etsug_intervals_sect009.htm
If you need more info or examples, please let me know.
Best of luck!
If you want to display the variable's contents as a date (without changing the underlying value), use a FORMAT statement.
proc print;
format dte mmddyys10.;
run;
proc means;
class dte;
format dte mmddyys10.;
run;
etc. Note that you can also put the FORMAT in a data step, in which case any uses of the variable will automatically pick it up.
data foo;
format dte mmddyys10.;
run;
My answer from a duplicate question:
You need to convert original SAS DATETIME value (think of it as data type) to SAS DATE value using DATEPART() function and apply appropriate format:
proc sql;
create table work.abc2
as select *, DATEPART(a.Billing_Dt) format ddmmyy10. as Bill_date
from abc;
quit;
So the point is, as Keith pointed above, to apply appropriate type of format (e.g. ddmmyy10. is the SAS Date format) to appropriate values = variable content (e.g. (unformatted) 10 is 11th January 1960 if used as date, while it's 01JAN60:00:00:10 if used as Datetime value), so you have to be sure what your values represent and convert the values if needed.
data want;
dt_val1='17JUL2006:00:00:00.000'dt;
dt_you_want=input(substr(put(dt_val1,datetime22.3),1,9),date9.);
format dt ddmmyy10.;
run;
Converts date/time var to char date var:
BLEndDatex = put(datepart(BLEndDateTime),yymmdd10.);
Create numeric sas date without time:
BLEndDate = mdy(SUBSTR(BLEndDatex,6,2),SUBSTR(BLEndDatex,9,2),SUBSTR(BLEndDatex,1,4));
Thanks to Rizier123 & Heemin posting above to the first portion.

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