SAS date formatting hours / minutes / seconds - datetime

Because my time data has some messy characters in it ( *, #, char, etc) I'm inputting the data in best.32 format and then using compress to remove the irrelevant char - time_1 = compress(Tim_original,'*#','l');
However, my data takes the form of mm:ss and hh:mm:ss and for some reason when I use time_1=input(time_1,time8.) to convert from the string to a num, it makes my mm into hours...! How do I covert my string to time/minutes and not have the minutes turned into hours with ":00" added at the end?

If your text only has one : then the informat TIME will take that to mean hh:mm and not mm:ss. You could just test your string and divide the result of the INPUT() function call by 60 to convert it.
data test;
input #1 timestr $8. ;
time1=input(timestr,time8.);
time2=input(timestr,time8.);
if countw(timestr,':') < 3 then time2=time2/60 ;
format time1 time2 time8.;
cards;
12:34
0:12:34
;

Related

Subtract number of hours from current time in Java

I have a string that represents time duration of 54:34:41 i.e. 54 hours, 34 minutes, 41 seconds.
I would like to extract the 54 hours and subtract it from the current system time.
However when I run below I get java.time.format.DateTimeParseException: Text '54:34:41' could not be parsed: Invalid value for HourOfDay (valid values 0 - 23): 54
How can I extract 54 hours and subtract from current time?
private val formatterForTime: DateTimeFormatter = DateTimeFormatter.ofPattern("HH:mm:ss")
val timeDuration = formatterForTime.parse("54:34:41")
val currentTime = LocalDateTime.now()
val newTime = currentTime.minusHours(timeDuration.get(ChronoField.HOUR_OF_DAY).toLong())
tl;dr
ZonedDateTime
.now(
ZoneId.of( "Asia/Tokyo" )
)
.minusHours(
Integer.parseInt( "54:34:41".split( ":" )[0] )
)
Details
Parse hours
Get the number of hours.
int hours = Integer.parseInt( "54:34:41".split( ":" )[0] ) ;
ISO 8601
Your input text for a span-of-time does not comply with the ISO 8601 standard for date-time values. The java.time classes by default use the standard formats when parsing/generating text.
If instead of 54:34:41 you had PT54H34M41S, then we could use:
int hours = Duration.parse( "PT54H34M41S" ).toHours() ;
I recommend you stick with the standard format rather than the ambiguous clock-time format.
Capture current moment
Capture the current moment as seen in a particular time zone.
ZoneId z = ZoneId.of( "Africa/Casablanca" ) ;
ZonedDateTime zdt = ZonedDateTime.now( z ) ;
Subtract hours
Subtract your hours.
ZonedDateTime earlier = zdt.minusHours( hours ) )

How to convert string column to time column type?

I have a column in this format
when I ingest the data, it is in a string format.
When I tried to convert it to timespan, the values disappear
How can I convert string column to timespan?
You could try using parse and then make_timespan(), or timespan arithmetics:
https://learn.microsoft.com/en-us/azure/data-explorer/kusto/query/make-timespanfunction
https://learn.microsoft.com/en-us/azure/data-explorer/kusto/query/datetime-timespan-arithmetic
https://learn.microsoft.com/en-us/azure/data-explorer/kusto/query/parseoperator
For example:
T
| parse event_time with minutes:int ":" seconds:int "." ms:int
| project result = minutes * 1m + seconds * 1s + ms * 100 * 1ms
Use the format_timespan Kusto function with fffffff formatter.
Example
format_timespan(time(29.09:00:05.12345), 'ddd.h:mm:ss [fffffff]')
Result: 029.9:00:05 [1234500]

Hive: Convert string datetime with missing seconds in "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"

I'm using the following code to convert a string datetime variable to datetime, but the converted string is missing SSS part.
Code used:
cast(FROM_UNIXTIME(UNIX_TIMESTAMP(oldtime, "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"),"yyyy-MM-dd HH:mm:ss.SSS") as timestamp) as newtime
The outcome:
2019-03-08T18:28:36.901Z is converted to 08MAR2019:18:28:36.000000
Some other oldtimes in string:
2020-03-09T16:05:06:827Z
2020-03-09T16:03:19:354Z
2020-03-11T16:03:57:280Z
2020-03-10T16:02:57:642Z
2020-03-10T16:04:07:455Z
2020-03-10T16:04:09:737Z
2020-03-10T16:03:57:280Z
2020-03-10T16:02:46:816Z
The SSS part '901' is missing in the converted time. Would like help on keeping the SSS part since I need to sort the records by their exact time.
Thank you!
from_unixtime is always until minutes(yyyy-MM-dd HH:mm:ss) to get millisecs we need to do some workarounds.
we will extract the millisecs from the old_time using regexp_extract then concat that to from_unixtime result and finally cast to timestamp.
Example:
select old_time,
timestamp(concat_ws(".", --concat_ws with . and cast
FROM_UNIXTIME(UNIX_TIMESTAMP(old_time, "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"),"yyyy-MM-dd HH:mm:ss"), -- from_unixtime and unix_timestamp to convert without millisecs
regexp_extract(string(old_time),".+\\.(.*)(?i)z",1))) as newtime from --regexp_extract to extract last 3 digits before z then concat
(select string("2020-03-11T21:14:41.335Z")old_time)e
+------------------------+-----------------------+
|old_time |newtime |
+------------------------+-----------------------+
|2020-03-11T21:14:41.335Z|2020-03-11 21:14:41.335|
+------------------------+-----------------------+
UPDATE:
Your sample data have : before milliseconds, Try with below query:
select old_time,
timestamp(concat_ws(".", --concat_ws with . and cast
FROM_UNIXTIME(UNIX_TIMESTAMP(old_time, "yyyy-MM-dd'T'HH:mm:ss:SSS'Z'"),"yyyy-MM-dd HH:mm:ss"), -- from_unixtime and unix_timestamp to convert without millisecs
regexp_extract(string(old_time),".+\\:(.*)(?i)z",1))) as newtime from --regexp_extract to extract last 3 digits before z then concat
(select string("2020-03-11T21:14:41:335Z")old_time)e
Simply replace 'T' with space ' ' remove 'Z' and replace last ':' with dot, like this :
select regexp_replace('2020-03-09T16:05:06:827Z','(.*?)T(.*?):([^:]*?)Z$','$1 $2\\.$3');
Result:
2020-03-09 16:05:06.827
Read also this answer if you need to convert to different format, preserving milliseconds: https://stackoverflow.com/a/59645846/2700344

Convert 15 digit number string to java8 timestamp

I am struggling to convert a big 15 digit number string to a date format.
Sample code :
String dateInString = "201410051252323";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ssZ");
LocalDateTime dateTime = LocalDateTime.parse(dateInString, formatter);
I am getting following exception
java.time.format.DateTimeParseException: Text '2014100591523' could not be parsed at index 0
Can anyone please suggest the best way to do this in Java 8
You have the right the idea, but there are two issues with your code--one syntactic, and the other logistic:
Your pattern expects the string to be formatted with hyphens and colons and spaces. For example, "yyyy-MM-dd" will match "2014-10-05", but not "20141005". To match the latter, just drop the hyphens and use "yyyyMMdd".
You use a 'Z' in your pattern for the final digit, indicating that you expect a time zone offset in your string. But the 'Z' pattern matches offsets like "+0000" and "-8000", not a single digit. Also, to represent datetimes with a time zone, you should use the ZonedDateTime or OffsetDateTime class instead of LocalDateTime
I'm not sure which time zone the '3' in your example string is supposed to represent, if it is indeed supposed to represent a zone offset at all. If you do not have control over the formatting of your data set, you'll have to peel off the final digit and handle it separately.
String dateInString = "201410051252323";
String dateTimeString = dateInString.substring(0, 14); // "20141005125232"
String zoneDigitString = dateInString.substring(14); // "3"
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss"); // no "Z"
LocalDateTime dateTime = LocalDateTime.parse(dateTimeString, formatter);
/* Manually convert zoneDigitString to a ZoneId here */
ZoneId zone = ...;
ZonedDateTime zonedDateTime = dateTime.atZone(zone);
You'll have to handle the "..." part on your own, depending on what "3" represents.

How to convert string to datetime format classic asp

I have one variable
Dim tt="2008-10-20 10:00:00.0000000"
I want to change it into date,
Try CDATE(tt) see http://www.w3schools.com/vbscript/func_cdate.asp. I used
vbscript cdate
as keywords at Google. There were more results.
Edit: Based on the comment below (I'm sorry for mixing up), using
FormatDateTime(date,format)
Format contains following constants:
0 = vbGeneralDate - Default. Returns date: mm/dd/yy and time if
specified: hh:mm:ss PM/AM.
1 = vbLongDate - Returns date: weekday, monthname, year
2 = vbShortDate - Returns date: mm/dd/yy
3 = vbLongTime - Returns time: hh:mm:ss PM/AM
4 = vbShortTime - Return time: hh:mm
(copied from http://www.w3schools.com/vbscript/func_formatdatetime.asp)
This link, (MS CDate page), explains that:
adate = CDate(astring)
converts a string into a date object. For there, you can format it with the FormatDateTime function
str = FormatDateTime(Date)
the FormatDateTime function is "smart" -- it will format as date and time if both are present, otherwise it will format with whichever of date or time is present.
I propose a safe solution which returns the result only if the conversion is successful:
s="2008-10-20 10:00:00.0000000"
On Error Resume Next
d=CDate(Left(s,19))
On Error Goto 0
if not IsEmpty(d) then MsgBox d
Try it for a non-valid date or non-valid format. The result will be empty.
s="2008-02-31 10:00:00"
In same contexts, it is necessary to initialize the variable collecting result of CData. I recommend to initialize it as Empty. Example below shows such case - counting valid dates in a string array:
Lines = array("2008-10-20 10:00:00.0000000", "2008-10-20 10:00:00", "", "2008-02-31", "Today", "2017-02-7")
On Error Resume Next
Count=0
for each Line in Lines
d=Empty
d=CDate(Line)
if not IsEmpty(d) then Count=Count+1
next
On Error Goto 0
MsgBox "Number of valid dates is "&Count
The correct answer is 2. Without initialization we get 5 as the CDate does not do anything on error so variable keeps the value from a recent iteration in the loop.
If do not need your milliseconds, your could use the following:
<script type="text/vbscript">
s="2008-10-20 10:00:00.0000000"
arr= Split(s, ".")
d=CDate(arr(0))
document.write(d)
</script>
I believe cdate is dependent on local settings to parse the string. This is no good in many situations.
To avoid this you need to use
DateSerial()
and if needed add any time components to the result separately.
The date literal in classic asp is unreliable. If the first or second part is greater than 12, it takes that value for day, the other as month. If both parts are less than 12, the interpretation is unpredictable: sometimes american and sometimes british.
A work-around is to force the entry of dates into separate fields or use a date entry module which can set the date into british or american style.
A date literal should be treated as american and use a function to convert that into a date variable using Dateserial().
function amerdate(str)
'str 3/5/2023 form: in american format: use for calculations including date
Dim d
d = Split(str, "/")
amerdate = Dateserial(d(2), d(0), d(1))
end function
Use only american date in calculations like Dateadd() etc.
someday = "3/5/2023" '5th march, american date literal
nextday = Dateadd("d", 1, amerdate(someday))
Whenever a date display is required, convert to british date and show it.
function britdate(str)
'str: 3/5/2023 form: display in british form. not for calculations
Dim d
d= Split(str, "/")
britdate = d(1) & "/" & d(0) & "/" & d(2)
end function

Resources