Split the date and time from string in codesys v 3 - stl

i 'm working on codesys . I have a string which has the DATE AND TIME .I want to split the date and time .
currentTime: DATE_AND_TIME;
showing value like this
DT#2019-08-06-10:06:53
after concat Convert the currentTime variable into string .
Now i want to split the date and time values
time : 10:06:53
Date 2019-08-06
Please provide the deceleration and implementation part

Declaration part:
dtDateAndTime : DATE_AND_TIME;
sDateAndTime : STRING;
sDate : STRING;
sTime : STRING;
Implementation part:
sDateAndTime := DT_TO_STRING(dtDateAndTime);
sDate := MID(sDateAndTime, 10 , 4);
sTime := RIGHT(sDateAndTime, 8);

Related

Spark DDL Schema JSON Struct

Question
I am trying to define a nested .json schema in pyspark, but cannot get the ddl_schema string to work.
Usually in SQL this would be ROW, I have tried STRUCT below but can't get the data type correct this is the error...
ParseException:
mismatched input '(' expecting {<EOF>, ',', 'COMMENT', NOT}(line 6, pos 15)
== SQL ==
driverId INT,
driverRef STRING,
number STRING,
code STRING,
name STRUCT(forename STRING, surname STRING),
---------------^^^
dob DATE,
nationality STRING,
url STRING
Data Sample
+--------+----------+------+----+--------------------+----------+-----------+--------------------+
|driverId| driverRef|number|code| name| dob|nationality| url|
+--------+----------+------+----+--------------------+----------+-----------+--------------------+
| 1| hamilton| 44| HAM| {Lewis, Hamilton}|1985-01-07| British|http://en.wikiped...|
Code Sample
mnt = "/mnt/dev/root"
env = "raw"
path = "formula1/drivers"
fileFormat = "json"
inPath = f"{mnt}/{env.upper()}/{path}.{fileFormat}"
options = {'header': 'True'}
ddl_schema = """
driverId INT,
driverRef STRING,
number STRING,
code STRING,
name STRUCT(forename STRING, surname STRING),
dob DATE,
nationality STRING,
url STRING
"""
drivers_df = (spark
.read
.options(**options)
.schema(ddl_schema)
.format(fileFormat)
.load(inPath)
)
You are using the wrong syntax for STRUCT.
Here is the right one:
name STRUCT<forename:STRING,surname:STRING>
https://spark.apache.org/docs/latest/sql-ref-datatypes.html
(search for Complex types and choose the SQL tab)
Data type
SQL name
BooleanType
BOOLEAN
ByteType
BYTE, TINYINT
ShortType
SHORT, SMALLINT
IntegerType
INT, INTEGER
LongType
LONG, BIGINT
FloatType
FLOAT, REAL
DoubleType
DOUBLE
DateType
DATE
TimestampType
TIMESTAMP
StringType
STRING
BinaryType
BINARY
DecimalType
DECIMAL, DEC, NUMERIC
YearMonthIntervalType
INTERVAL YEAR, INTERVAL YEAR TO MONTH, INTERVAL MONTH
DayTimeIntervalType
INTERVAL DAY, INTERVAL DAY TO HOUR, INTERVAL DAY TO MINUTE, INTERVAL DAY TO SECOND, INTERVAL HOUR, INTERVAL HOUR TO MINUTE, INTERVAL HOUR TO SECOND, INTERVAL MINUTE, INTERVAL MINUTE TO SECOND, INTERVAL SECOND
ArrayType
ARRAY<element_type>
StructType
STRUCT<field1_name: field1_type, field2_name: field2_type, …> Note: ‘:’ is optional.
MapType
MAP<key_type, value_type>

SQL Server - Convert datetime to JSON date format

How can I convert SQL smalldatetime or datetime like this:
select cast(getdate() as smalldatetime)
To JSON format like this:
/Date(1576278000000+0100)/
I just find this post in another issue like you got it.
Maybe it would work for you
"render": function ( data, type, row ) {
var fecha = new Date(parseInt(data.match(/\d+/)[0]));
return fecha.getMonth() + 1 + '/' + fecha.getDate() + '/' + fecha.getFullYear();;
},
"targets": 0
and this is the link that I found
https://es.stackoverflow.com/questions/125686/convertir-fecha-en-javascript

Random number using Date() in Expression Builder

I want to generate random number using Date() to format it like for example: ddmmyyyyHhNnSs
How do I achieve that? Is that even possible?
I was kinda hoping I can do it easy way by the expression builder but I seem to fail on each approach ;)
This number need to populate txtID field and it will be unique identifier for each database entry.
That's quite easy - with a twist.
Problem is that Rnd only returns a Single and the resolution of this only allows for 10000000 unique values. As you request a resolution to the second and with 86400 seconds per day, that only leaves a span of 115.74 days while the range of Date spans 3615899 days:
TotalDays = -CLng(#1/1/100#) + CLng(#12/31/9999#)
To overcome this, use Rnd twice which will result in 1E+15 possible values or 11574074074 days - way beyond what's needed:
RandomDouble = Rnd * Rnd
Now, to limit the possible values to fit into the range of data type Date, just follow the documentation:
RandomValue = (UpperValue - LowerValue) * Rnd + LowerValue
and apply the date values:
RandomDouble = (CLng(#12/31/9999#) - CLng(#1/1/100#)) * Rnd * Rnd + CLng(#1/1/100#)
This, however, will result in values containing unwanted milliseconds, thus perform the proper conversion to Date value using CDate which will round to the nearest second, and you have the final expression:
RandomDate = CDate((CLng(#12/31/9999#) - CLng(#1/1/100#)) * Rnd * Rnd + CLng(#1/1/100#))
Use the value as is if your field is of datatype Date or - if text - apply a format to this with Format(RandomDate, "yyyymmddhhnnss") and a sample output will be:
01770317032120
01390126010945
50140322081227
35290813165627
09330527072433
20560513105943
61810505124235
09381019130230
17010527033132
08310306233911
If you want numeric values, use CDec to convert (CLng will fail because of overflow):
RandomNumber = CDec(Format(RandomDate, "yyyymmddhhnnss"))
All said, I'm with #Bohemian - if you just want a unique timestamp and have less than one transaction per second, just use data type Date for your field and use Now:
TimeStamp = Now()
and apply a format to this of yyyymmddhhnnss.
However, Multiplying random numbers together alters the
probablility distribution:
Uniform Product Distribution
Thus, a better method is to create a random date, then a random time, and possibly a random count of milliseconds - I wrote above, that CDate rounds a value to the nearest second; it doesn't, only whenever Access displays a date/time with milliseconds the displayed valued is rounded to the second.
So I modified the function to take care of this:
Public Function DateRandom( _
Optional ByVal UpperDate As Date = #12/31/9999#, _
Optional ByVal LowerDate As Date = #1/1/100#, _
Optional ByVal DatePart As Boolean = True, _
Optional ByVal TimePart As Boolean = True, _
Optional ByVal MilliSecondPart As Boolean = False) _
As Date
' Generates a random date/time - optionally within the range of LowerDate and/or UpperDate.
' Optionally, return value can be set to include date and/or time and/or milliseconds.
'
' 2015-08-28. Gustav Brock, Cactus Data ApS, CPH.
' 2015-08-29. Modified for uniform distribution as suggested by Stuart McLachlan by
' combining a random date and a random time.
' 2015-08-30. Modified to return selectable and rounded value parts for
' Date, Time, and Milliseconds.
' 2015-08-31. An initial call of Randomize it included to prevent identical sequences.
Const SecondsPerDay As Long = 60& * 60& * 24&
Dim DateValue As Date
Dim TimeValue As Date
Dim MSecValue As Date
' Shuffle the start position of the sequence of Rnd.
Randomize
' If all parts are deselected, select date and time.
If Not DatePart And Not TimePart And Not MilliSecondPart = True Then
DatePart = True
TimePart = True
End If
If DatePart = True Then
' Remove time parts from UpperDate and LowerDate as well from the result value.
' Add 1 to include LowerDate as a possible return value.
DateValue = CDate(Int((Int(UpperDate) - Int(LowerDate) + 1) * Rnd) + Int(LowerDate))
End If
If TimePart = True Then
' Calculate a time value rounded to the second.
TimeValue = CDate(Int(SecondsPerDay * Rnd) / SecondsPerDay)
End If
If MilliSecondPart = True Then
' Calculate a millisecond value rounded to the millisecond.
MSecValue = CDate(Int(1000 * Rnd) / 1000 / SecondsPerDay)
End If
DateRandom = DateValue + TimeValue + MSecValue
End Function
Format now() and cast to a long:
select CLng(format(now(), 'ddmmyyyyhhnnss')) as txnId
Although this is not "random", it is unique as long as there are never more than one transaction per second (confirmed in comment above).

Error in plpgsql function: array value must start with "{" or dimension information

I'm trying to format the results of this query:
CREATE OR REPLACE FUNCTION "alarmEventList"(sampleid integer
, starttime timestamp without time zone
, stoptime timestamp without time zone)
RETURNS text[] AS
$BODY$DECLARE
result text[];
BEGIN
select into result array_agg(res::text)
from (
select to_char("Timestamp", 'YYYY-MM-DD HH24:MI:SS')
,"AlertLevel"
,"Timestamp" - lag("Timestamp") over (order by "Timestamp")
from "Judgements"
WHERE "SampleID" = sampleid
and "Timestamp" >= starttime
and "Timestamp" <= stoptime
) res
where "AlertLevel" > 0;
select into result array_to_string(result,',');
return result;
END
$BODY$
LANGUAGE plpgsql VOLATILE
Right now without array_to_string() I get something like this:
{"(\"2013-10-16 15:10:40\",1,00:00:00)","(\"2013-10-16 15:11:52\",1,00:00:48)"}
and I want something like this:
2013-10-16 15:10:40,1,00:00:00 | 2013-10-16 15:11:52,1,00:00:48 |
But when I run the query I get error:
array value must start with "{" or dimension information
You do not actually want an array type, but a string representation.
Can be achieved like this:
CREATE OR REPLACE FUNCTION "alarmEventList"(sampleid integer
, starttime timestamp
, stoptime timestamp
, OUT result text) AS
$func$
BEGIN
SELECT INTO result string_agg(concat_ws(','
,to_char("Timestamp", 'YYYY-MM-DD HH24:MI:SS')
,"AlertLevel"
,"Timestamp" - ts_lag)
, ' | ')
FROM (
SELECT "Timestamp"
,"AlertLevel"
,lag("Timestamp") OVER (ORDER BY "Timestamp") AS ts_lag
FROM "Judgements"
WHERE "SampleID" = sampleid
AND "Timestamp" >= starttime
AND "Timestamp" <= stoptime
) res
WHERE "AlertLevel" > 0;
END
$func$ LANGUAGE plpgsql
The manual on string_agg() and concat_ws().

problem with convert text to time in sql server 2008?

i have this Ttime as nvarchar(10): "09:52:48" and i have TmpTime as date
and i try to convert like this: "UPDATE MEN SET TmpTime = CONVERT(DATETIME, Ttime ,108 )"
and i get in TmpTime this: "1900-01-01"
why ?
thank's in advance
If you also have a date field, you should to concatenate them before to cast:
CREATE TABLE #Sample ( DateField varchar(10), TimeField varchar(10) );
GO
INSERT INTO #Sample VALUES ('2009-01-24', '09:52:48');
SELECT CONVERT(DATETIME, DateField + ' ' + TimeField) as Converted FROM #Sample
And you'll get:
Converted
-----------------------
2009-01-24 09:52:48.000
You have a column defined as "date" and then you are sending only a time value into it
The date portion defaults to zero which is 01 January 1900 in SQL (in the CONVERT). Then the time is ignored for a date column.
What do you expect to happen?
(The same would happen whether or not you use CONVERT or not because the column is "date")