fly36
fly36

Reputation: 83

How to combine date and time into one variable using Stata

My database is a panel dataset which contains variable name, date, time.

The format of date looks like this 02jan2002. time is a artificial time stamp whose value is between 20 and 32. I want to combine date and time and create a new variable, so I can tsset this variable.

Can anyone tell me how to combine these two variables?

Upvotes: 0

Views: 2434

Answers (2)

dimitriy
dimitriy

Reputation: 9460

Here's one way to do it:

clear
set obs 3
gen id = _n
expand 2
bys id: gen date = 20200 + _n
format date %td
expand 13
bys id date: gen time = _n+19
sort id date time

gen double ts = dhms(date,round((time)*30/60,1)-1,mod(time*30+30,60),0.000)
format ts %tcDDmonCCYY_HH:MM
tsset id ts, delta(30 minutes)

The idea behind this is the same as Nick's solution, though his is more efficient. I convert the time interval variable into hours and into minutes. I feed these to the dhms() function, which expects the first argument to be a %td date variable, the second to be hours, the third to be minutes, and the last to be seconds.

Upvotes: 1

Nick Cox
Nick Cox

Reputation: 37208

To tsset or to xtset the data all that is needed are integer dates or datetimes. But here it seems that you have no observations over most of the day, i.e. only 6 hr 30 min of observations each day and 17 hr 30 min of gaps.

You would need a convention to use one time and one time only for each 30 min period. Choosing the beginning of each period as one convention, you could generate date-times using

gen double datetime = cofd(date) + (time - 1) * 30 * 60000
format %tc 

given that date appears to be a Stata daily date variable and that time encodes 30 minute intervals and there are 60000 ms in each minute.

In declaring identifier and time, you would need to specify delta(1800000),

As said, the gaps are made obvious by this declaration. Whether you need a fiction that the clock stops when observations are not being made is an open question.

Upvotes: 1

Related Questions