In Power Bi, I have a table that contains Name and TimeSpent by user in seconds.
I want to convert total seconds spent by all users into duration format (hh:mm)
When I am getting seconds in hh:mm format for each user from database query, the values are coming up like these 12:63 etc. After importing these values into power bi, I tried to set its datatype to DateTime format but power bi shows an error saying that it is not a valid value. If I set the datatype of the column as string then strings dont add up.
What can be the ideal way to do it?
you can solve this in one line:
measure = FORMAT(TIME(0;0;tableNAME[your_column]);"HH:mm:ss")
You can try the following DAX:
HHMMSS =
INT(Table[TimeSpent] / 3600) & ":" &
RIGHT("0" & INT((Table[TimeSpent] - INT(Table[TimeSpent] / 3600) * 3600) / 60), 2) & ":" &
RIGHT("0" & MOD(Table[TimeSpent], 3600), 2)
Source
Had a similar question but for D:HH:MM:SS, code below if it's of use.
DurTime (meas) =
VAR vDur = <<<duration in CALCULATE(SUM(seconds)) >>>
RETURN INT(vDur/86400) & ":" & //Days
RIGHT("0" & INT(MOD(vDur/3600,24)),2) & ":" & //Hours
RIGHT("0" & INT(MOD(vDur/60,60)),2) & ":" & //Minutes
RIGHT("0" & INT(MOD(vDur,60)),2) //Seconds
DAX code:
= TIME(0,0,SUM('Table'[Timespent]))
Then click the modelling tab and choose Format - Date Time and choose the appropriate format.
That's a better formula, which I'm using in PBI:
HHMMSS = FORMAT(TIME(int(Table[TimeSpent] / 3600); int(mod(Table[TimeSpent]; 3600) / 60);int(mod(mod(Table[TimeSpent]; 3600); 60))); "HH:mm:ss")
I wanted a Power BI Measure wich is easy to read for this problem, code below if it's of use.
HH:MM =
VAR TotalDuration = SUM(tableNAME[your_column] ) //if you use a measure just leave the SUM part out
VAR TotalHours = TRUNC (TotalDuration/3600)
VAR Min_ = FORMAT(TRUNC(TotalDuration - TotalHours * 3600),"00")
RETURN
TotalHours & ":" & Min_
The solution is adopted from the top answer of this question PowerBi Duration calculation in hh:mm:ss
Related
Asking for some help here, im trying to convert text to time in duration format on Google Sheets, i´ve used some basic fuctions to to breakdown text (with delimiters as d (days) h (hour) m(minute) and s(second) into values that were then baked into a time function, however for outputs over 24 hours I was unable to get it to format properly i.e. in the image below 375 hrs should show 375:00:00 or [H]:mm:ss
Any ideas here?
Sharing the doc
https://docs.google.com/spreadsheets/d/1YWHM5tPaLOulHMbfdR8CZJsER7LBceWLQrm9f8JcV9c/edit#gid=0
Try, in J12
=(G12+H12/60+I12/60/60)/24
then apply duration format
try:
=FLATTEN(INDEX(QUERY(, "select "&TEXTJOIN(",", 1,
SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(B7:B27,
"d", "*86400"), "h", "*3600"), "m", "*60"), "s", "*1"), " ", "+")))/86400, 2))
Use regexextract(), like this:
=arrayformula(
iferror(regexextract(B7:B, "(\d+)\s*h"), 0) & ":" &
iferror(regexextract(B7:B, "(\d+)\s*m"), 0) & ":" &
iferror(regexextract(B7:B, "(\d+)\s*s"), 0)
)
The formula gives text strings. To get numeric durations, use value(), like this:
=arrayformula(
iferror( 1 /
value(
iferror(regexextract(B7:B, "(\d+)\s*h"), 0) & ":" &
iferror(regexextract(B7:B, "(\d+)\s*m"), 0) & ":" &
iferror(regexextract(B7:B, "(\d+)\s*s"), 0)
)
^ -1 )
)
Format the result column as Format > Number > Duration.
In the event there are many components in the text string you are converting, it may be beneficial to use just one regextextract(), which is possible using the recently introduced lambda functions:
=arrayformula(
map(
B7:B,
lambda(
duration,
if(
len(duration),
join(
":",
iferror(
regexextract(
duration,
{ "(\d+)\s*h"; "(\d+)\s*m"; "(\d+)\s*s" }
),
0
)
),
iferror(1/0)
)
)
)
)
See this answer for an explanation of how date and time values work in spreadsheets.
How to calculate Duration of Time between two date time through VBscript
Date1 = 2021-01-22 11:43:38.000
Date2 = 2021-01-22 14:32:38.000
result should be HH:MM:SS
TimeSerial and FormatDateTime return a date or time that will take the regional settings of the computer into account. On my European computer no AM extension is shown because we use the 24h time format.
An additional problem with TimeSerial is that it will overflow once there are more than 32767 seconds.
A different approach could be to calculate the values for hours, minutes and seconds separately. A possible solution could be:
secValue = DateDiff("s",Date1,Date2)
hours = secValue \ 3600
hh = hours
if hours < 10 then
hh = Right("0" & hours, 2)
end if
mm = Right("0" & (secValue - hours * 3600) \ 60, 2)
ss = Right("0" & secValue mod 60, 2)
diff = hh & ":" & mm & ":" & ss
wscript.echo diff
Finally i answered to my Question Feeling great
Date1 = alA_Filling(0)
Date2 = alA_Filling(1)
secValue = DateDiff("s",Date1,Date2)
ts = TimeSerial(0, 0, secValue)
Duration = FormatDateTime(ts, vbLongTime)
But i got output like 2:49:00 AM why added AM to this may be this vbLongTime
how can i remove that AM
I am writing a macro that processes an excel with lots of data. One of the rows contains a date range like wkstartdate - wkenddate and I would like to use dateadd function to print next date range every week (like '27-01-14 - 02-02-14' in below case) but unable to do so.
'06-01-14 - 12-01-14'
'13-01-14 - 19-01-14'
'20-01-14 - 26-01-14'
I used below excerpt which fails:
Range("E" & Lastrow).Select
prwk = Split(ActiveCell.Value, "-")
'curr_wkstart = DateAdd("d", 7, prwk(1)) 'error as maybe prwk(1) isnt correct format
'curr_wkend = DateAdd("d", 7, prwk(2)) 'error
Range("E" & Lastrow + 1).Value = curr_wkstart & curr_wkend 'no result
For testing purpose I print, prwk(1) which is 20/01/14 in the above case, in a diff cell and add 7 days, which gives me 1/21/2020 instead of '27/01/14'. I also tried using Cdate function, but still error
Can you please advise??
I think what you want to use here are the Format and DateSerial functions. Here's how I came at it:
Function GetNextWeek(TheStartWeek)
a = Split(TheStartWeek, " - ")
b = Split(a(1), "-")
c = DateSerial(b(2), b(1), b(0)) + 1
d = c + 6
GetNextWeek = Format(c, "dd-mm-yy") & " - " & Format(d, "dd-mm-yy")
End Function
Sub Test()
Debug.Print GetNextWeek("13-01-14 - 19-01-14") 'Givs you "20-01-14 - 26-01-14"
End Sub
Hope this helps.
I have an array of Epoch milliseconds (array of numbers) in Matlab. I would like to convert these into UTC date-time format, such as DD-MM-YYYY HH:MM.
Is there a pre-defined Matlab way to do this or will I have to write my own function?
Suppose, you start with a vector time_unix, then:
>> time_unix = 1339116554872; % example time
>> time_reference = datenum('1970', 'yyyy');
>> time_matlab = time_reference + time_unix / 8.64e7;
>> time_matlab_string = datestr(time_matlab, 'yyyymmdd HH:MM:SS.FFF')
time_matlab_string =
20120608 00:49:14.872
Notes:
1) See the definition of matlab's time.
2) 8.64e7 is number of milliseconds in a day.
3) Matlab does not apply any time-zone shifts, so the result is the same UTC time.
4) Example for backward transformation:
>> matlab_time = now;
>> unix_time = round(8.64e7 * (matlab_time - datenum('1970', 'yyyy')))
unix_time =
1339118367664
To summarize, here are two functions:
function tm = unix2matlab(tu)
tm = datenum('1970', 'yyyy') + tu / 864e5;
end
function tu = matlab2unix(tm)
tu = round(864e5 * (tm - datenum('1970', 'yyyy')));
end
The matlab time here is numeric. You can always convert it to string using datestr()
Update for nanoseconds
time_unix_nanos = 1339116554872666666;
millis = round(time_unix_nanos / 1e6);
nanos = time_unix_nanos - 1e6 * millis;
time_matlab = unix2matlab(millis);
s = [datestr(time_matlab, 'yyyymmdd HH:MM:SS.FFF'), num2str(nanos)];
s =
20120608 00:49:14.872666666
I tried the above code, but the results were wrong. I realised the main error is related to the awkward definition of the Unix time (epoch time). Unix time (epoch time) is defined as the number of seconds after 1-1-1970, 00h:00, not the number of **milli**seconds (http://en.wikipedia.org/wiki/Unix_time). With this definition, the Unix time should therefore be divided by 8.64e5 instead of 8.64e7.
In addition, datenum('1970', 'yyyy') does not seem to result in the desired reference time of 1-1-1970, 00h:00.
Here's my improved code:
tMatlab = datenum (1970,1,1,0,0) + tUnix / 86400;
Serg's answer is what I normally use, when I'm working in MATLAB. Today I found myself wanting to do the conversion to date in MATLAB as the title says - without the datestring conversion specified in the question body - and output the date number from the shell.
Here is what I settled on for the rounded date number:
TODAY_MATLAB="$[719529 + $[`date +%s` / 24/60/60]]"
This is really just the bash equivalent of what you would expect: 719529 is the datenum of the epoch (1970-01-01 or datenum(1970,1,1) in MATLAB). I'm also fumbling through ksh lately and it seems this can be done there with:
TODAY_EPOCH=`date +%s`
TODAY_MATLAB=`expr $TODAY_EPOCH / 24 / 60 / 60 + 719529`
As a side exercise, I added the decimal portion back onto the date in bash - I didn't bother in ksh, but it's only arithmetic and goes similarly:
N_DIGITS=7
FORMAT=$(printf "%%d.%%0%dd" $N_DIGITS)
NOW_EP_SEC=`date +%s`
SEC_PER_DAY=$(( 24*60*60 ))
NOW_EP_DAY=$(( $NOW_EP /$SEC_PER_DAY ))
SEC_TODAY=$(( $NOW_EP_SEC - $NOW_EP_DAY*$SEC_PER_DAY ))
TODAY_MATLAB="$(( NOW_EP_DAY+719529 ))"
FRACTION_MATLAB="$( printf '%07d' $(( ($SEC_TODAY*10**$N_DIGITS)/SEC_PER_DAY )) )"
MATLAB_DATENUM=$( printf $FORMAT $TODAY_MATLAB $FRACTION_MATLAB )
echo $MATLAB_DATENUM
I want the date to look like MM-DD-YYYY instead of MM/DD/YYYY.
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
d=CDate("2010-02-16 13:45")
document.write(FormatDateTime(d) & "<br />")
document.write(FormatDateTime(d,1) & "<br />")
document.write(FormatDateTime(d,2) & "<br />")
document.write(FormatDateTime(d,3) & "<br />")
document.write(FormatDateTime(d,4) & "<br />")
If you want to use another format you will have to create your own function and parse Month, Year, Day, etc and put them together in your preferred format.
Function myDateFormat(myDate)
d = TwoDigits(Day(myDate))
m = TwoDigits(Month(myDate))
y = Year(myDate)
myDateFormat= m & "-" & d & "-" & y
End Function
Function TwoDigits(num)
If(Len(num)=1) Then
TwoDigits="0"&num
Else
TwoDigits=num
End If
End Function
edit: added function to format day and month as 0n if value is less than 10.
Suggest calling 'Now' only once in the function to guard against the minute, or even the day, changing during the execution of the function.
Thus:
Function timeStamp()
Dim t
t = Now
timeStamp = Year(t) & "-" & _
Right("0" & Month(t),2) & "-" & _
Right("0" & Day(t),2) & "_" & _
Right("0" & Hour(t),2) & _
Right("0" & Minute(t),2) ' '& _ Right("0" & Second(t),2)
End Function
The output of FormatDateTime depends on configuration in Regional Settings in Control Panel. So in other countries FormatDateTime(d, 2) may for example return yyyy-MM-dd.
If you want your output to be "culture invariant", use myDateFormat() from stian.net's solution. If you just don't like slashes in dates and you don't care about date format in other countries, you can just use
Replace(FormatDateTime(d,2),"/","-")
'for unique file names I use
Dim ts, logfile, thisScript
thisScript = LEFT(Wscript.ScriptName,LEN(Wscript.ScriptName)-4) ' assuming .vbs extension
ts = timeStamp
logfile = thisScript & "_" & ts
' ======
Function timeStamp()
timeStamp = Year(Now) & "-" & _
Right("0" & Month(Now),2) & "-" & _
Right("0" & Day(Now),2) & "_" & _
Right("0" & Hour(Now),2) & _
Right("0" & Minute(Now),2) ' '& _ Right("0" & Second(Now),2)
End Function
' ======
This snippet also solve this question with datePart function. I've also used the right() trick to perform a rpad(x,2,"0").
option explicit
Wscript.Echo "Today is " & myDate(now)
' date formatted as your request
Function myDate(dt)
dim d,m,y, sep
sep = "-"
' right(..) here works as rpad(x,2,"0")
d = right("0" & datePart("d",dt),2)
m = right("0" & datePart("m",dt),2)
y = datePart("yyyy",dt)
myDate= m & sep & d & sep & y
End Function
Although answer is provided I found simpler solution:
Date:
01/20/2017
By doing replace
CurrentDate = replace(date, "/", "-")
It will output:
01-20-2017
For anyone who might still need this in the future. My answer is very similar to qaweb, just a lot less intimidating. There seems to be no cool automatic simple function to formate date in VBS. So you'll have to do it manually. I took the different components of the date and concatenated them together.
Dim timeStamp
timeStamp = Month(Date)&"-"&Day(Date)&"-"&Year(Date)
run = msgbox(timeStamp)
Which will result in 11-22-2019 (depending on the current date)