Announcement

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

  • converting strings to dates

    I know that this is covered elsewhere, but I can't get the code to work. I have dates that look like this (let's call this variable "var"):

    Examples: "2019-08-19 12:16:00"
    "2020-11-19 20:41:21"
    "2021-11-22 16:14:37"
    "2022-08-19 11:08:01"

    I try the following code (I have tried about two dozen variations of this, all with the same result):

    gen double var_n = clock( var , "YMDHMS")

    The result is that var_n consists only of missing values, so none of the dates are converted. I have seen this behavior typically if the format is not correctly specified, but I have tried every variation on the format specification that I can think of, and nothing works. Other variables being converted where they are dates without times (using different code, but a similar approach) works fine. I feel that I must be missing something obvious, but I am just not seeing it. I'm hoping someone can quickly see what I am doing wrong? Thanks in advance for any help!

  • #2
    The specification of the mask is biting you. Note the lower caps for hours, minutes and seconds.

    Code:
    * Example generated by -dataex-. For more info, type help dataex
    clear
    input str29 date
    "2019-08-19 12:16:00"
    "2020-11-19 20:41:21"
    "2021-11-22 16:14:37"
    "2022-08-19 11:08:01"
    end
    
    gen double wanted = clock(date, "YMDhms")
    format wanted %tc
    Res.:

    Code:
    . l
    
         +------------------------------------------+
         |                date               wanted |
         |------------------------------------------|
      1. | 2019-08-19 12:16:00   19aug2019 12:16:00 |
      2. | 2020-11-19 20:41:21   19nov2020 20:41:21 |
      3. | 2021-11-22 16:14:37   22nov2021 16:14:37 |
      4. | 2022-08-19 11:08:01   19aug2022 11:08:01 |
         +------------------------------------------+

    Comment


    • #3
      I imagine the syntax was resolved thus:

      1. The date() function, later paralleled by the daily() function, was introduced to get numeric daily dates out of strings, with syntax Y M D for elements indicating years, months, and days.

      2. The clock() function, introduced later, needed syntax as similar as possible, but M was already bespoke for month. Hence h m s as extra syntax for elements indicating hours, minutes, and seconds.

      Comment


      • #4
        Thanks! This solved the conversion issue.

        Comment

        Working...
        X