Announcement

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

  • Convert a date variable with a character

    I have data stored like this:
    01-JAN-2020 02:20
    I'd like to convert it to clock
    gen eventdate = clock(datetime_str_numeric, "DMYhms")

    Is there any easy way to do this or do I have to use a substring command?

  • #2
    Code:
    clear
    input str20 y
    "01-JAN-2020 02:20"
    end
    gen double eventdate = clock(y, "DM20Yhm")
    format eventdate %tcDD-NN-CCYY_HH:MM
    Last edited by Ken Chui; 15 Dec 2023, 13:09.

    Comment


    • #3
      Here is what I did that works but is inefficient:

      gen datetime_str_numeric = subinstr(incidentdatetime, "JAN", "01", 1)
      replace datetime_str_numeric = subinstr(datetime_str_numeric, "FEB", "02", 1)
      replace datetime_str_numeric = subinstr(datetime_str_numeric, "MAR", "03", 1)
      replace datetime_str_numeric = subinstr(datetime_str_numeric, "APR", "04", 1)
      replace datetime_str_numeric = subinstr(datetime_str_numeric, "MAY", "05", 1)
      replace datetime_str_numeric = subinstr(datetime_str_numeric, "JUN", "06", 1)
      replace datetime_str_numeric = subinstr(datetime_str_numeric, "JUL", "07", 1)
      replace datetime_str_numeric = subinstr(datetime_str_numeric, "AUG", "08", 1)
      replace datetime_str_numeric = subinstr(datetime_str_numeric, "SEP", "09", 1)
      replace datetime_str_numeric = subinstr(datetime_str_numeric, "OCT", "10", 1)
      replace datetime_str_numeric = subinstr(datetime_str_numeric, "NOV", "11", 1)
      replace datetime_str_numeric = subinstr(datetime_str_numeric, "DEC", "12", 1)

      Comment


      • #4
        The conversions in #3 are all unnecessary. @Ken Chui's solution shows that clock() is fine with months in the form JAN.

        There were two problems with the code in #1. clock() was expecting seconds as well and didn't find them. The variable type must be double. This is emphasised repeatedly in help datetime.

        Comment

        Working...
        X