Announcement

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

  • date function converts dates to different dates

    Hello,

    Could anyone help me with this problem?

    I've converted the date and stata adds or subtract a few minutes like below:


    For example, the string variable is "2021-07-16 10:00", the converted one is "2021-07-16 9:58"

    The command I used are these

    generate hour3 = clock(hour2,"YMDhm")
    format %tcCCYY-NN-DD_hh:MM hour3

    please help me.
    Attached Files

  • #2
    Code:
    generate double hour3 = clock(hour2,"YMDhm")
    Or better:
    Code:
    set type double, permanently

    Comment


    • #3
      As Joseph Coveney exemplifies, and as help datetime documents repeatedly, you need a double to hold date-times accurately.

      Everything is driven by the fact that some Stata users deal with times recorded in milliseconds. (In practice, there are people like physicists who need even finer time resolutions, but if they use Stata and are missing this, they aren't visibly agitating about their needs.) With data like those in #1 the numbers are in trillions, and Stata can get close but often not as close as is wanted if you use a float.

      Take one of those times

      Code:
      . di %tc clock("2021-07-10 10:00", "YMD hm")
      10jul2021 10:00:00
      The number you need to hold is

      Code:
      . di %18.0f  clock("2021-07-10 10:00", "YMD hm")
           1941530400000
      In my Stata I don't change the default type away from float, so I get this

      Code:
      . gen foo = clock("2021-07-10 10:00", "YMD hm")
      
      . di %18.0f foo[1]
           1941530345472
      That's the closest I can get with a float, and it is off by 54528 milliseconds.

      (At the moment I can't explain why your result appears 2 minutes off, rather than about 1 minute.)

      This may be clearer in binary.

      What you have is

      Code:
      . inbase 2 `=foo[1]'
      11100010000001100001110100000000000000000
      whereas what you need is

      Code:
      . inbase 2 `= clock("2021-07-10 10:00", "YMD hm")'
      11100010000001100001110101101010100000000
      .In short, you need many more bits that are contained in a float.

      Comment


      • #4
        Joseph Coveney , Nick Cox
        Thank you so much guys!
        I truly appreciate your advices, I really do.
        ​​​​​​​Thank you very much.

        Comment

        Working...
        X