Announcement

Collapse
No announcement yet.
X
  • Filter
  • Time
  • Show
Clear All
new posts

  • Add seconds/minutes/hour to a datetime stata

    Hello everyone,

    Let's say that I have a date/time variable (vardt) formatted as %tc. how can I add one second to the variable. For example, if the vardt is 12jan2015 17:01:11, I need 12jan2015 17:01:12. Also how can I add 1 minute and hours?

    Thank you in advance,
    Marvin

  • #2
    The output of help datetime tells us that the values of datetime variables are stored as

    milliseconds since 01jan1960 00:00:00.000
    Thus, adding 1000 to a datetime values increases it by one second; adding 60,000, by 1 minute; adding 3,600,000, by 1 hour.

    Comment


    • #3
      thank you William. I also found that you can add minutes , hours by using the following command replace START_DT= START_DT+ msofseconds(1)

      Comment


      • #4
        I find it easier to work out the number in question 1000, 60000, 60000*60, ..., as the case may be than to read help datetime to find the name of the function that returns the constant!

        Comment


        • #5
          Just s a reference for future readers (or myself in the future).

          Make sure your numeric (datetime) variable is double. Otherwise one loses precious precision.

          Example. Create a time series of 15 min long blocks since 1996-01-03 07:45 hs. Then, the first observation is 08:00hs, then 08:15 hs, 08:30hs and so on.

          For example, this will not work as intended.
          Code:
          set obs 3
          gen DATETIME = _n *(60*15*1000) + clock("1996-01-03 07:45:00.0", "YMD hms")
          results in
          3/01/1996 08:00
          3/01/1996 08:15
          3/01/1996 08:31
          Do you see that unexpected 08:31?

          Specifying double as variable type corrects it.
          Code:
          set obs 3
          gen double DATETIME = _n *(60*15*1000) + clock("1996-01-03 07:45:00.0", "YMD hms")
          See help data_types and help datetime_translation##intro

          Comment

          Working...
          X