To calculate elapsed time between two timestamp attributes

Hello,
I have two timestamp attributes (create_tmstmp & elapsed_tmstmp) in a table.
It has two rows and I need the difference in seconds between these two attributes.
The below query is returning negative value and incorrect value.
Any help is appreciated.
Row 1:
Create_tmstmp : 2/2/2010 9:53:15.832 PM
Elapsed_tmstmp : 2/3/2010 9:49:47.527 AM
Row 2:
Create_tmstmp : 2/3/2010 5:35:47.614 AM
Elapsed_tmstmp : 2/3/2010 11:03:15.937 AM
Select
( (extract(day from elapsed_tmstmp )-extract(day from create_tmstmp))*86400+
(extract(hour from elapsed_tmstmp )-extract(hour from create_tmstmp))*3600+
(extract(minute from elapsed_tmstmp)-extract(minute from create_tmstmp))*60+
(extract(second from elapsed_tmstmp)-extract(second from create_tmstmp))*1000) completed_tmstmp
From table_a;
The output is :
completedtmstmp_
74655
-11997
Thanks.
Edited by: solsam on Feb 4, 2010 11:57 AM

hi,
The problem with cast to date is
SQL> select to_char(cast(to_timestamp('2/2/2010 9:53:15.832 PM','mm/dd/yyyy hh:mi:ss.ff pm') as dat
e),'mm/dd/yyyy hh:mi:ss pm') from dual
2 ;
TO_CHAR(CAST(TO_TIMEST
02/02/2010 09:53:16 pm
so cast rounds it up, resulting in:
SELECT (
CAST (TO_TIMESTAMP ('2/2/2010 9:53:15.832 PM', 'mm/dd/yyyy hh:mi:ss.ff pm') AS DATE)
- CAST (TO_TIMESTAMP ('2/2/2010 9:53:14.432 PM', 'mm/dd/yyyy hh:mi:ss.ff pm') AS DATE)
* 86400 x
FROM DUAL
X
2
A more exact answer would use, to_char and to_date to convert :
SELECT (
TO_DATE (TO_CHAR (TO_TIMESTAMP ('2/2/2010 9:53:15.832 PM', 'mm/dd/yyyy hh:mi:ss.ff pm'),
'mm/dd/yyyy hh:mi:ss pm'),
'mm/dd/yyyy hh:mi:ss pm')
- TO_DATE (TO_CHAR (TO_TIMESTAMP ('2/2/2010 9:53:14.432 PM', 'mm/dd/yyyy hh:mi:ss.ff pm'),
'mm/dd/yyyy hh:mi:ss pm'),
'mm/dd/yyyy hh:mi:ss pm')
* 86400 x
FROM DUAL
X
1
Edit:
Massimo Ruocchio's answer actually works better.
-AC
Edited by: user12026137 on Feb 9, 2010 12:45 PM

Similar Messages

  • How to Calculate the Time Between two days in ABAP

    Hi,
                  I have one scenario like i need to calculate the time between two days please can you suggest me.
    Thanks,
    Harinath

    Hi Peeleti,
                Check this code,
    DATA : DATE1 LIKE SY-DATUM VALUE '19830125',
           DATE2 LIKE SY-DATUM VALUE '20070219',
           DAYS1 TYPE I,
           WEEK1 TYPE I,
           MONTH1 TYPE I,
           YEAR1 TYPE I,
           C_YEARS1 TYPE I.
    CALL FUNCTION 'HR_99S_INTERVAL_BETWEEN_DATES'
    EXPORTING
      BEGDA           = DATE1
       endda           = DATE2
      TAB_MODE        = ' '
    IMPORTING
      DAYS            = DAYS1
      C_WEEKS         =
      C_MONTHS        = C_YEARS1
      C_YEARS         = C_YEARS1
      WEEKS           = WEEK1
      MONTHS          = MONTH1
      YEARS           = YEAR1.
      D_MONTHS        =
      MONTH_TAB       =
    *WRITE : / 'DAYS   = ', DAYS1,
            / 'WEEKS = ',WEEK1,
          /  'MONTHS = ', MONTH1,
          / 'YEARS   = ', YEAR1.
    Using this code you can calculate the No Of Days Between two dates. Based On days you will easily calculate the Hour. [  No of days * 24 ].
    Thanks.
    Reward If helpful.

  • Calculate elapsed Workhours between 2 timestamps

    Hi,
    Is there any function that would return the number of workhours between 2 timestamps in the tool depending upon the calendar defined. It would be great if someone could provide any inputs of the way to calculate this.
    Thanks,
    Sree

    There would be a bit of code involved but here's one approach to calculating the number of working hours based on calendar rules.
    There's an OOTB method that returns the number of days between to times based on a specific Calendar rule:
    calendar as Fuego.Lib.CalendarRule
    workDays as Int
    calendar = CalendarRule.fetch(calendarName : "US_STD")
    elapsedDays calendar
        using fromDate = 'now',
              toDate = futureDate
        returning workDays = workDaysIf you have to have the number of hours, you'd first have to find out how many working days are left in today:
    totalHours as Int - 0
    todayStartLaborTime as Time
    todayEndLaborTime as Time
    closeTime(CalendarRule, time : 'now', out endLaborTime : todayEndLaborTime)
    startTime(CalendarRule, time : 'now', out startLaborTime : todayStartLaborTime)
    // are we already in the workday?
    if todayStartLaborTime < 'now' && todayEndLaborTime > 'now' then
        // get the number of work hours left today
        timedifference = todayEndLaborTime - 'now'
        totalHours = totalHours + timedifference.hours
    // workday not started today?
    elseif todayStartLaborTime > 'now' then
        timedifference = todayEndLaborTime - todayStartLaborTime
        totalHours = totalHours + timedifference.hours
    endThen you would need to see how many hours are in the final working day:
    futureStartLaborTime as Time
    futureStartLaborTime as Time
    futureEndLaborTime as Time
    startTime(CalendarRule, time : futureDate, out startLaborTime : futureStartLaborTime)
    closeTime(CalendarRule, time : futureDate, out endLaborTime : futureEndLaborTime)
    // how many hours in the last workday are there?
    if futureDate > futureStartLaborTime && futureDate < futureEndLaborTime then 
        // get the number of work hours left that day
        timedifference = futureStartLaborTime - futureDate
        totalHours = totalHours + timedifference.hours 
    end Finally, you'd want to loop through the days between the start and end days (non-inclusively) and get the number of working hours in each day.
    nextStartTime as Time
    nextEndTime as Time
    previousDayEndTime as Time = 'now'
    while previousDayEndTime < futureDate do
        // get the next day's start and end times
        nextWorkDayStartTime calendar
            using time = previousDayEndTime
            returning nextStartTime = nextStartTime
        nextWorkDayCloseTime calendar
            using time = previousDayEndTime
            returning nextEndTime = nextCloseTime
        timedifference = nextEndTime - nextStartTime
        totalHours = totalHours + timedifference.hours
        previousDayEndTime = nextEndTime
    endHope this helps,
    Dan

  • How to find the elapsed time between 2 events ?

    I want to use the robot class and I have register all events in a file but when I use the Robot. It isn't synchronous. So I should find th elapsed time between two events for reproducing them with the method delay of the class Robot.
    Thanks

    It sounds like you want to reproduce the events with varying time between the events? This is a good idea for a couple of reasons 1) it's possible to enqueue events so quickly that Robot gets ahead of the Java GUI, and 2) every human does their mouse/keyboard activity at varying (and relatively slow, relative to the computer that is) rates of speed. It would help make a more realistic interaction to vary the speed of event reproduction.
    Since you can't control the amount of time between the call to Robot and when the event arrives in the application, you can't be ultimately precise about this. You'll have to accept a teensy bit of slop in the process and just live with it.
    That is ... you can do something like robot.method1() .. Thread.sleep(1) .. robot.method2() .. Thread.sleep(1) ... and that will give slight delays. If you vary the value for Thread.sleep you can vary the event reproduction speed. Early in the development of Robot I experimented with something like this - I set up an EventQueue listener to capture all mouse/keyboard events (remember that each comes with a timestamp) and then reproduced events using the time intervals from the captured events to control the Thread.sleep times between Robot calls. It worked pretty well, and the mouse would dance around in the same way I moved the mouse around.
    - David

  • Calculate the difference between two dates times in infopath form 2013

    Hi,
    I have an infopath 2013 form that contains three fields:
    2 date time and the 3rd contains the difference between the two in hours
    how I can make the difference between the two so that the display will be like this:
    Date Time1           08/21/2014           22:00 
    Date Time2           08/22/2014           1:00
    Diff Field                                             3:00

    Hi,
    Please refer to the following article which matches your requirement exactly.
    Calculate the difference between two date picker controls in InfoPath using rules and formulas - no code!
    Please mark it answered, if your problem resolved.

  • When using historical datalogging, is it possible to hide the elapsed time between tag updates when viewing on a graph?

    When my process stops, I am reading an array of tags(datapoints) and writing the max and average to memory tags for data logging. However, when viewing the data, the elapsed time between cycles spreads the data out unevenly. It could be 90 seconds between cycles or maybe two hours or longer. Is there a way to convert the time axis data to be just consecutive datapoints?? It would be like logging data based on a particular condition happening rather than time-based trending. Should I try to use the data set logger examples instead?? I would prefer to use the built-in datalogging features rather than writing to databases.

    You could export your data to a spreadsheet file and then actually write then again in a second database using this example program in the devzone
    http://zone.ni.com/devzone/conceptd.nsf/webmain/5A921A403438390F86256B9700809A53?opendocument
    Using this program (if you don't want to modify it, which would take a reasonable amount of time specially if you are not familiar with VI-Based Server) You would have to generate a collum in your spreadsheet file to be the timestamp, it would be a artificial timestamp.
    What you could do in your application is to first save the data to file and then read from file, substitute the collum timestamp for the "artificial one" and then write it to the database, again, with that you would not need to modify this program.
    However if you have the time and is willing to work with VI-based server you could try to modify the example program to be adapted for your purposes.
    I hope it helps
    Good Luck
    Andre Oliveira
    Applications Engineer
    National Instruments

  • Diff between two timestamp in minutes on case condition

    Hi Gurus,
    I wanted to find the diff between two timestamp in minutes on case condition
    when type=1 then min(col2) and type=2 then max(col2)
    type-(datatype-numeric)
    col2-(datatype-timestamp)
    how can i do this
    Thanks

    Hi,
    Is this a question about the Berkeley DB SQL product?
    If so, you should look at the documentation on time fields in the SQLite page here:
    http://www.sqlite.org/datatype3.html#datetime
    Otherwise, you are asking this on the wrong forum.
    Regards,
    Alex Gorrod
    Oracle Berkeley DB.

  • Calculate the Difference Between two dates excluding weekends and Holidays

    Hi,
    We need to calculate the difference between the two dates by excluding the Local public holidays (It is global and varies across countries) and weekends should not be included in calculation for a business day in OBIEE.
    We have two dates: Open date and close date when ever close date is null we are calculating age based on taking the current timestamp and need to exclude the weekends and Holidays when ever the close date is null.
    Ex:
    Col1 col2 Total
    11/9/2010 2:46:38 PM Null 13
    11/2/2010 8:06:26 PM 11/3/2010 5:37:03 PM 1
    (In the Total we shouldn't include the weekends,holidays)
    Please let me know how to calculate the difference between two dates by excluding the weekends and holidays.
    Thanks
    Edited by: user10441472 on Nov 22, 2010 3:14 PM

    You already asked this question and I answered it...
    Re: calculation of Business day in OBIEE

  • Use more than one transition in the same time between two video clips?

    Dear Premiere Pro programmers,
    Could you please create a way to use more than one transition in the same time between two video clips without exporting to media, or creating new sequence, or using another layer (adjustment or transparent)?
    Message was edited by: Kevin Monahan
    Reason: Next time, create a more descriptive title.

    Hi Aqsa Nori,
    I'm not sure what you are imagining, but it might be possible to achieve by key framing effects. Can you tell us what you want to do? Also, please feel free to file a feature request: http://adobe.ly/feature_request
    Thanks,
    Kevin

  • How to count time between two pulses

    Hello everyone,
    I want to count time between two boolean pulses?  Can anyone give me an advice? Thank you in advance!

    Hello Michael78,
    You've right. I have a DAQ board and i want to acquire torque and angle (from a torque transducer). I already done that, but sometimes it doesn't work properly. To acquire this, i count sign changing of the torque to acquire exactly one period (3 sign changing). Torque have a noise, and when passes through zero, count more than 3 sign changing at a time, and this stop my acquisition (figure 2). I want to set a time between 2 counting sign . I tried something with tick count...but i made something wrong . I hope you understand me....
    Attachments:
    Capture.PNG ‏51 KB
    Capture2.PNG ‏47 KB
    Capture3.PNG ‏123 KB

  • Difference between two timestamp.

    Hi,
    I want to find difference between two timestamp in minutes.
    Actually i want to retrieve difference between current timestamp and the timestamp taken from the table
    select log_time from serv_info where server_id = 1;
    Can anyone tell me the query to find difference between two timestamps in minutes.
    -haifriends

    SQL> WITH serv_in AS
         (SELECT SYSTIMESTAMP - 1 / 4 log_time,
                 SYSTIMESTAMP now
            FROM DUAL)
    SELECT log_time,
           now,
             24 * 60 * EXTRACT (DAY FROM (now - log_time))
           + 60 * EXTRACT (HOUR FROM (now - log_time))
           + EXTRACT (MINUTE FROM (now - log_time))
           + 1 / 60 * EXTRACT (SECOND FROM (now - log_time)) diff_in_minutes
      FROM serv_in
    LOG_TIME  NOW                                 DIFF_IN_MINUTES
    01-MRZ-07 01-MAR-07 03.47.42.107462 PM +01:00      360,001791

  • Calculate the difference between two dates

    I would like to calculate the difference between two dates in PL/SQL and return the result as a number of days expressed as an integer value.

    Denes,
    A fair point, I should really have posted this on the SQL forum (I'm new to the forum as well as PL/SQL) but thanks for responding anyway. It does raise a question as to how to implement this in ApEx though.
    I have created the function and am calling it as shown below from the source window of a form. The source type is 'PL/SQL expression or function' and the expression in the source window of the form is:
    calc_date_difference (:p26_c_payment, :p26_c_rec)
    The two parameters being passed are of type date but I'm not sure how to handle the ruturned number and populate the form in ApEx with this value.
    Is it possible to do it this way or am I taking completely the wrong approach?
    Regards
    Sandy
    This is not ApEx related but SQL related:
    CREATE OR REPLACE FUNCTION calc_date_difference (
    p_date_1   VARCHAR2,
    p_date_2   VARCHAR2
    RETURN NUMBER
    v_difference   NUMBER;
    v_sql_err      VARCHAR2 (4000);
    BEGIN
    v_difference := TRUNC (TO_DATE (p_date_1)) - TRUNC
    (TO_DATE (p_date_2));
    RETURN v_difference;
    CEPTION
    WHEN OTHERS
    THEN
    v_sql_err := SQLERRM || CHR (10) || CHR (10) ||
    SQLCODE;
    ND calc_date_difference;and
    SQL> SELECT calc_date_difference ('23.01.2007',
    '20.01.2007') diff
    2    FROM DUAL;
    DIFF
    3
    Denes Kubicek                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

  • Calculate the variance between two row

    Post Author: jane
    CA Forum: WebIntelligence Reporting
    Hi,
    I'm new to BO and wondering whether there is a way to calculate the variance between two rows. I'm working on a report which requires to display the change of two day's data. For instance, I have a table in a format as
    Date
    Sales Amount
    3/12/2008
    2300.00
    2/12/2008
    1280.00
    Changed
    1020.00
    I'd like to display the "Changed" column. Is there a way to do that in BO InfoView? In Excel, you can use the formular by identify the two cells.
    Thanks!

    Post Author: Vinl
    CA Forum: WebIntelligence Reporting
    I am having the same problem and am steping outside of the box and cannot progress.
    Seems to me that you are kind of saying that the only way to get around this is to create an individual object in Designer? I cannot find a way of cementing values as a variable in order for a variance to be created.
    I am trying to do it at column level mind you, which should not make that much difference....
    Simple SQL database. I have created an object called "Year" which takes a date and converts it to a year. I then have another object created "Total sales", put the 2 in a table get the right results...try and create a year on year variance from that...no chance...
    Used to work ok...?

  • How to get the time difference (in seconds) between two timestamp fields?

    Hi All,
    I'm exploring validation expressions in SAP MDM Data Manager version 7.1.07.245
    I have two timestamp fields, suppose Update Date and Update-GDS.
    What I'm trying to do is prompt a warning when:
    (Update Date minus Update-GDS) is greater than or equal to zero seconds
    AND
    (Update Date minus Update-GDS) is less than or equal to 900 seconds
    the bottomline is, Update Date must be equal or greater than to Update-GDS but Update Date must not exceed 900 seconds difference.
    my initial try was:
    (Update Date - Update-GDS)>=0 s AND (Update Date - Update-GDS)<=900 s
    But it always returns true even the time difference between update date and update-gds is beyond the condition.
    Can you please guide me through this?
    Thank you very much in advance.
    Regards,
    ~erwin

    Hi Abhishek,
    I tried your code but it always returns true.
    It seems subtraction of timestamp fields do not actually get the time difference... (in seconds)
    Is this possible anyway? Or is there any other better approach on this?
    Thanks,
    ~erwin
    Edited by: erwin.j.rivera on Dec 14, 2011 8:40 AM

  • Need a sql query to get the difference between two timestamp in the format of hh:mm:ss.msec

    I have a database table where it keeps record of the transaction when it starts at StartTime and when it ends at EndTime. Both these entries are having the timestamp entries. Say for example, I have a tuple with Entries like 'Transaction A' starts at '2014-05-07
    20:55:03.170' and ends at '2014-05-08 08:56:03.170'. I need to find the difference between these two timestamps and my expected output is 12:01:00.000. Let me know how to achieve this ? 

    Hi,
    You can use below script which calculates difference as DD:HH:MM:SS. You can modify the same:
    DECLARE @startTime DATETIME
    DECLARE @endTime DATETIME
    SET @startTime = '2013-11-05 12:20:35'
    SET @endTime = '2013-11-10 01:22:30'
    SELECT [DD:HH:MM:SS] =
    CAST((DATEDIFF(HOUR, @startTime, @endTime) / 24) AS VARCHAR)
    + ':' +
    CAST((DATEDIFF(HOUR, @startTime, @endTime) % 24) AS VARCHAR)
    + ':' +
    CASE WHEN DATEPART(SECOND, @endTime) >= DATEPART(SECOND, @startTime)
    THEN CAST((DATEDIFF(MINUTE, @startTime, @endTime) % 60) AS VARCHAR)
    ELSE
    CAST((DATEDIFF(MINUTE, DATEADD(MINUTE, -1, @endTime), @endTime) % 60)
    AS VARCHAR)
    END
    + ':' + CAST((DATEDIFF(SECOND, @startTime, @endTime) % 60) AS VARCHAR),
    [StringFormat] =
    CAST((DATEDIFF(HOUR , @startTime, @endTime) / 24) AS VARCHAR) +
    ' Days ' +
    CAST((DATEDIFF(HOUR , @startTime, @endTime) % 24) AS VARCHAR) +
    ' Hours ' +
    CASE WHEN DATEPART(SECOND, @endTime) >= DATEPART(SECOND, @startTime)
    THEN CAST((DATEDIFF(MINUTE, @startTime, @endTime) % 60) AS VARCHAR)
    ELSE
    CAST((DATEDIFF(MINUTE, DATEADD(MINUTE, -1, @endTime), @endTime) % 60)
    AS VARCHAR)
    END +
    ' Minutes ' +
    CAST((DATEDIFF(SECOND, @startTime, @endTime) % 60) AS VARCHAR) +
    ' Seconds '
    Reference:
    http://sqlandme.com/2013/12/23/sql-server-calculating-elapsed-time-from-datetime/
    - Vishal
    SqlAndMe.com

Maybe you are looking for

  • How do I combine text and image on same screen?

    How do I comgine text and an image on the same screen in Final Cut Express 4.  I have had to use scrolling text and then import a graphic.  I want the text and graphic on the same page.  Thanks .

  • Logical Path of  wsdl

    Hi, I´m developing a Adaptive Web service Model in Webdynpro and i´m facing a problem trying to create a model, I don´t know how can i find the logical destination of the wsdl created on xi scenario, i need to give this path to be able to create the

  • IPhone not syncing - "Unknown Error -50"

    Just starting today, I've been having trouble syncing my iPhone 3G (3.0.1) to my computer. I get the "Unknown Error -50" towards the end of the sync, after backup, etc. I reset the iPhone, restored the software and restarted the computer. I used the

  • Different servers for dialup-access and exec-access

    Hi all, I am trying to configure a 3640 for authorization. The 'tricky' part is that I have to make a difference between dialup-access on one hand and exec-access on the other hand. I am using TACACS+ for authentication and authorization. The origina

  • Adobe Reader PlugIn issue

    I installed Adobe reader on Mac.  I want to open pdfs on safari in Adobe.  When in Safari the pdf's are not opening in safari.  Can someone help?Adober Reader PlugIn issue