How to bound time using Stata?

2019-08-15 05:24发布

I want to restrict TRD_EVENT_TM variable of my dataset, which is time value, between 9:30 t0 11:00.

* Example generated by -dataex-. To install: ssc install dataex
clear
input str8 TRD_EVENT_TM str6 TRD_STCK_CD double TRD_PR long TRD_EVENT_DT
"09:53:17" "BANK1"   909 18293
"10:25:40" "HSHM1"  1706 19205
"11:32:03" "SIPA1"  2231 18866
"11:01:55" "AZAB1"  2283 18916
"12:19:56" "SIPA1"  2063 17683
"10:48:01" "CHML1"  6048 18672
"10:59:49" "DADE1"  3044 18847
"11:40:34" "CHML1"  6406 18798
"10:54:45" "GOLG1"  7583 18544
"11:08:01" "IKCO1"  3942 18743
"10:25:35" "ASIA1"  5248 18511
"09:41:46" "FOLD1"  4910 19406
"11:43:15" "BANK1"   829 18105
end
format %tdD_m_Y TRD_EVENT_DT

How can I do that?

标签: time stata
2条回答
干净又极端
2楼-- · 2019-08-15 05:55

Although it's a string variable, the condition inrange(TRD_EVENT, "09:30", "11:00") should work fine. With your data,

. list TRD_EVENT_TM if inrange(TRD_EVENT_TM, "09:30", "11:00") , sep(0) 

     +----------+
     | TRD_EV~M |
     |----------|
  1. | 09:53:17 |
  2. | 10:25:40 |
  6. | 10:48:01 |
  7. | 10:59:49 |
  9. | 10:54:45 |
 11. | 10:25:35 |
 12. | 09:41:46 |
     +----------+

help inrange() documents that the function allows string arguments. See also https://www.stata-journal.com/sjpdf.html?articlenum=dm0026

查看更多
The star\"
3楼-- · 2019-08-15 05:56

An alternative approach is to use the built-in clock() function:

list TRD_EVENT_TM if clock(TRD_EVENT_TM, "hms") >= clock("9:30", "hm") & ///
clock(TRD_EVENT_TM, "hms") <= clock("11:00", "hm")

    +----------+
    | TRD_EV~M |
    |----------|
 1. | 09:53:17 |
 2. | 10:25:40 |
 6. | 10:48:01 |
 7. | 10:59:49 |
 9. | 10:54:45 |
    |----------|
11. | 10:25:35 |
12. | 09:41:46 |
    +----------+

So if you want to restrict the variable, you can simply create a new one containing the relevant observations:

generate NEW_TRD_EVENT_TM = TRD_EVENT_TM if ///
clock(TRD_EVENT_TM, "hms") >= clock("9:30", "hm") & ///
clock(TRD_EVENT_TM, "hms") <= clock("11:00", "hm")
查看更多
登录 后发表回答