【问题标题】:Range of times strings in StataStata中的时间字符串范围
【发布时间】:2021-02-18 23:21:58
【问题描述】:

我正在使用一个 Stata 数据集,该数据集以一种相当奇怪的方式保存了一段时间,在一个带有单词“to”的字符串中作为时间范围的指示,并带有十二小时时钟的标记,例如,“2020 年 3 月 20 日下午 1 点到下午 3 点”我想知道解析/使用这些信息的最佳方式是什么,尤其是对于datetime。我已通读 datetime 文档,虽然它对一天中的特定时间很有用,但在涉及时间范围时并不是特别有用。

我正在考虑将字符串分成两个字符串,时间范围的开始和结束,例如“2020 年 3 月 20 日下午 1 点”和“2020 年 3 月 20 日下午 3 点”,但我很好奇是否有更直接的解决方案可以使这些数据变得可行。我对我的方法的主要关注是如果时间间隔超过午夜自动更改日期,例如“2020 年 3 月 20 日晚上 11 点至凌晨 1 点”。任何建议将不胜感激。

这是一些示例数据:

input str28 times

"17may2020 1 p.m. to 10 p.m."
"17may2020 10 p.m. to 5 a.m." 
"18may2020 5 a.m. to noon"
"18may2020 noon to 7 p.m."
"18may2020 7 p.m. to 1 a.m."

【问题讨论】:

  • 请提供一个使用dataex 的数据示例,其中包括您提到的标准案例和跨越午夜的边缘案例。正如您所建议的,该解决方案可能涉及分隔字符串。
  • @Cyber​​nike 已编辑
  • 没有必要为一个好问题道歉。

标签: stata


【解决方案1】:
clear
input str28 times
"17may2020 1 p.m. to 10 p.m."
"17may2020 10 p.m. to 5 a.m." 
"18may2020 5 a.m. to noon"
"18may2020 noon to 7 p.m."
"18may2020 7 p.m. to 1 a.m."
end

// Noon won't be recognized by clock(), so replace with 12 p.m.
replace times = subinstr(times, "noon", "12 p.m.", .)

// Split times in two variables
gen times_only = substr(times, 11, .)
split times_only , parse("to")

// Generate datetime variables
gen double datetime1 = clock(substr(times,1,10) + times_only1, "DMYh")
gen double datetime2 = clock(substr(times,1,10) + times_only2, "DMYh")
format datetime1 datetime2 %tc

// If datetime2 is before datetime1, add one day (86400000 milliseconds)
replace datetime2 = datetime2 + 86400000 if datetime2 < datetime1

// Drop auxiliary variables
drop times_only*

// Admire the results
list

     +-----------------------------------------------------------------------+
     |                       times            datetime1            datetime2 |
     |-----------------------------------------------------------------------|
  1. | 17may2020 1 p.m. to 10 p.m.   17may2020 13:00:00   17may2020 22:00:00 |
  2. | 17may2020 10 p.m. to 5 a.m.   17may2020 22:00:00   18may2020 05:00:00 |
  3. | 18may2020 5 a.m. to 12 p.m.   18may2020 05:00:00   18may2020 12:00:00 |
  4. | 18may2020 12 p.m. to 7 p.m.   18may2020 12:00:00   18may2020 19:00:00 |
  5. | 18may2020 7 p.m. to 12 a.m.   18may2020 19:00:00   19may2020 00:00:00 |
     +-----------------------------------------------------------------------+

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-09-18
    • 1970-01-01
    • 1970-01-01
    • 2023-03-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多