以Stata表示的时间字符串范围

以Stata表示的时间字符串范围,stata,Stata,我正在使用一个Stata数据集,它以一种非常奇怪的方式保存时间段,字符串中的“to”表示时间范围,带有12小时时钟的标记,例如“20march2020下午1点到3点”。我想知道解析/使用此信息的最佳方式是什么,特别是关于datetime。我已经阅读了datetime文档,虽然它对一天中的特定时间很有用,但对于时间范围却没有特别的帮助 我曾考虑将字符串分为两个字符串,以时间范围的开始和结束为准,例如“20march2020下午1点”和“20march2020下午3点”,但我想知道是否有更直接的解决

我正在使用一个Stata数据集,它以一种非常奇怪的方式保存时间段,字符串中的“to”表示时间范围,带有12小时时钟的标记,例如“20march2020下午1点到3点”。我想知道解析/使用此信息的最佳方式是什么,特别是关于
datetime
。我已经阅读了
datetime
文档,虽然它对一天中的特定时间很有用,但对于时间范围却没有特别的帮助

我曾考虑将字符串分为两个字符串,以时间范围的开始和结束为准,例如“20march2020下午1点”和“20march2020下午3点”,但我想知道是否有更直接的解决方案使此数据可行。我对我的方法的主要担忧是,如果时间间隔超过午夜,则自动更改日期,例如“20点2020年3月11日下午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."
清除
输入str28次
“2020年5月17日下午1时至10时。”
“2020年5月17日下午10时至上午5时。”
“2020年5月18日上午5时至中午”
“2020年5月18日中午至下午7时。”
“2020年5月18日下午7时至凌晨1时”
结束
//时钟()无法识别中午,因此替换为下午12点。
替换时间=次仪表(时间,“中午”,“下午12点”
//在两个变量中拆分时间
gen times_only=substr(次,11,.)
仅拆分时间,解析(“到”)
//生成日期时间变量
gen double datetime1=时钟(substr(时间,1,10)+仅时间1,“DMYh”)
gen double datetime2=时钟(substr(时间,1,10)+仅时间2,“DMYh”)
格式化datetime1 datetime2%tc
//如果datetime2在datetime1之前,请添加一天(86400000毫秒)
如果datetime2
请使用
dataex
提供一个数据示例,其中包括您提到的标准案例和午夜时分的附带案例。正如您所建议的那样,解决方案可能包括分离字符串。@Cybernike Edited不必为一个好问题道歉。
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 |
     +-----------------------------------------------------------------------+