Mean value of data with varying time step - vb.net

I have a number of dataseries with timestep varying between a few seconds and maybe 120 minutes represented in decimal hours after January 1st. For example one value can be given at time 4692.759994 and the next at 4692.769281. The values can be both positive and negative. I would like to calculate mean values for any given time (usually 1 hour) and wonder of somebody have made anything similar. The code will probable in VBA or VB.net.
Thanks

If you use vb.net you might find this useful:
Dim dtbase As New DateTime(Now.Year, 1, 1)
Dim t1 As DateTime = dtbase.AddHours(4692.759994)
Dim t2 As DateTime = dtbase.AddHours(4692.769281)
Dim Interval As TimeSpan = t2 - t1 'the result is 00:00:33.4340000

Related

How to calculate time between dates on a report viewer expression

I have a program that uses report viewers to show various types of data to the user, and I need one of them to (basically) calculate the days between two dates WITHOUT weekends (i.e: from Friday to Monday, should show 2 and not 4).
So far, I can calculate it but with the weekends.
If anyone knows how, I'll appreciate it.
Code sample:(the formula i use on one of my tables as a expression)
CInt(Avg(DateDiff(dateinterval.DayOfYear,
Fields!DataEntregue.Value,
Fields!DataPrevista.Value,
FirstDayofWeek.Monday)))
From this question, I have converted Alec Pojidaev's (not accepted) answer to VB. I also returned an integer instead of double:
Public Shared Function GetBusinessDays(startD As DateTime, endD As DateTime) As Integer
Dim calcBusinessDays As Double = 1 + ((endD - startD).TotalDays * 5 - (startD.DayOfWeek - endD.DayOfWeek) * 2) / 7
If CInt(endD.DayOfWeek) = 6 Then
calcBusinessDays -= 1
End If
If CInt(startD.DayOfWeek) = 0 Then
calcBusinessDays -= 1
End If
Return CInt(calcBusinessDays)
End Function
Usage:
GetBusinessDays(date1, date2)
BTW, in the future, what you were looking for was how to calculate number of business days between two dates in [enter language here]. A quick web search for this would have brought you to a number of answers.

Inserting Datetime into Predefined 15min Intervals

I have a table with Datetime value and outbound call numbers. I need to be able to round the datetime down to the lower 15min interval, which is fine when I use DATEADD(mi,DATEDIFF(mi,0,[callplacedtime])/15*15, 0).
What I need to do now is for eg. if my search parameter is between 08:00:00 to 20:00:00 then I need to see '0' for the intervals where there were no data.
At the moment if there are not records in a specific interval then it doesn't show.
The trouble you're having is because there's no call numbers with datetimes within that range, SQL doesn't know that those datetimes exist or need to be shown.
Try using a numbers table to generate all the 15-minute offset times for the day, and then do a LEFT join from those 15-minute values to your current dataset. This means that all the times will exist, but if there are no call numbers for that 15-minute block, you'll get a NULL to interpret as you please.
I'm not familiar with SQL, but you could have an If/ElseIf/Else statement along the lines of:
If second = 0 then displaysecond = "00"
Elseif 0 < second < 10 then displaysecond = "0" + second
Else displaysecond = second

Find the number of days passed since January 1 of a particular year in vba

I want to find the number of days passed since January 1 from a date I provide.
Example :
Input - 12/01/2015
Output - 12
Input - 02/02/2015
Output - 33
I need the shortest possible way to do this. Please tell me if there is any function available in vb for this.
This should do it: (input in cell C4 .. or replace C4 with your input)
=C4-DATE(YEAR(C4)-1,12,31)
(I looked at DAYS360() first, but that one isn't the same math OP needs, so not a good choice there)
and yeah, no vba needed .. I'd just stick with a normal formula if you can ;)
VBA can be a bit slower sometimes, and harder to maintain ...
DatePart("y", dt) is one way, and possibly the shortest, where dt is your date.
Alternatively, you can use =A1 - DATE(YEAR(A1), 1, 0) directly on a worksheet, where A1 holds a date.
In VBA, just subtract the dates:
intDays = dt1 - #1/1/2015# ' Date literals use #
Dates are stored internally in VBA as Double, with "days" as the integer portion and "time" as the decimal portion. You can always just subtract one from another to determine the difference in number of days.

sqlalchemy select by date column only x newset days

suppose I have a table MyTable with a column some_date (date type of course) and I want to select the newest 3 months data (or x days).
What is the best way to achieve this?
Please notice that the date should not be measured from today but rather from the date range in the table (which might be older then today)
I need to find the maximum date and compare it to each row - if the difference is less than x days, return it.
All of this should be done with sqlalchemy and without loading the entire table.
What is the best way of doing it? must I have a subquery to find the maximum date? How do I select last X days?
Any help is appreciated.
EDIT:
The following query works in Oracle but seems inefficient (is max calculated for each row?) and I don't think that it'll work for all dialects:
select * from my_table where (select max(some_date) from my_table) - some_date < 10
You can do this in a single query and without resorting to creating datediff.
Here is an example I used for getting everything in the past day:
one_day = timedelta(hours=24)
one_day_ago = datetime.now() - one_day
Message.query.filter(Message.created > one_day_ago).all()
You can adapt the timedelta to whatever time range you are interested in.
UPDATE
Upon re-reading your question it looks like I failed to take into account the fact that you want to compare two dates which are in the database rather than today's day. I'm pretty sure that this sort of behavior is going to be database specific. In Postgres, you can use straightforward arithmetic.
Operations with DATEs
1. The difference between two DATES is always an INTEGER, representing the number of DAYS difference
DATE '1999-12-30' - DATE '1999-12-11' = INTEGER 19
You may add or subtract an INTEGER to a DATE to produce another DATE
DATE '1999-12-11' + INTEGER 19 = DATE '1999-12-30'
You're probably using timestamps if you are storing dates in postgres. Doing math with timestamps produces an interval object. Sqlalachemy works with timedeltas as a representation of intervals. So you could do something like:
one_day = timedelta(hours=24)
Model.query.join(ModelB, Model.created - ModelB.created < interval)
I haven't tested this exactly, but I've done things like this and they have worked.
I ended up doing two selects - one to get the max date and another to get the data
using the datediff recipe from this thread I added a datediff function and using the query q = session.query(MyTable).filter(datediff(max_date, some_date) < 10)
I still don't think this is the best way, but untill someone proves me wrong, it will have to do...

First Day Of Month For Calculated Number Of Months

I'm running into an issue where I need some more guidance. I've got a form that allows users to enter a start date and end date to represent the length of a contract. I'm using the following query to calculate the monthly amount :
SELECT t_Actuals.InvoiceAmount,
(DateDiff("m",[StartDate],[EndDate])+1) AS [Contract Term],
CCur(Round(([InvoiceAmount]/[Contract Term]),0)) AS MonthlyAmount
FROM t_Actuals;
Our VP wants the MonthlyAmount projected throughout the length of the Contract Term (ie. 11 months from Start Date). Ideally, I would like to allocate the MonthlyAmount in a MM-YYYY (01/2012, 02,2012) format throughout the length of the contract term, but, admittedly, I am not that experienced with working with dates in Access outside of the Query Grid.
Regardless, I've been reading about the DateSerial function to find the first day of the month, but how would you implement that into a loop to find the value of the first date of the month for the next 36 months and write that date to a table with the projected date as fldDate and MonthlyAmount.
Sorry, this is kind of a convuluted question. Any advice would be greatly appreciated. Thank you in advance for any direction.
"a loop to find the value of the first date of the month for the next 36 months and write that date to a table with the projected date as fldDate and MonthlyAmount"
Given the starting date of the first month and the number of months, you can use the DateAdd() function to determine the rest of the dates you need to insert. Open your table as a DAO recordset, use its .AddNew method to add a row, assign the values you want in the fields, and call .Update to store the row.
Sounded like your challenge was for the date piece, so I sketched that out and left the MonthlyAmount piece for you to complete.
Public Sub LoadMonthStartDates(ByVal pFirstDate As Date, _
ByVal pMonths As Long)
Const cstrTable = "YourTableNameHere"
Dim db As DAO.database
Dim rs As DAO.Recordset
Dim i As Long
Set db = CurrentDb
Set rs = db.OpenRecordset(cstrTable, dbOpenTable, dbAppendOnly)
For i = 1 To pMonths
rs.AddNew
rs!fldDate = DateAdd("m", i - 1, pFirstDate)
'rs!MonthlyAmount = <your calculated amount>
rs.Update
Next
rs.Close
Set rs = Nothing
Set db = Nothing
End Sub