# Date conversion

How can I calculate the time difference between two time recorded on tablet in STATA.

The time format are as follows:
Start Time : 2018-05-21T01:37:33
End Time: 2018-05-21T01:35:57

This the format for time collected from Survey Solution

I want to extract hh:mm:ss from these. How can I do that.

Thank you

Hello Tshering and thank you for the question.

1. Your listed end time is strangely before the start time. I assume this is just an example, but if this is real data, you may want to inspect what is going on.
2. In Stata you don’t need to get the hours from the timestamp to calculate the duration. The whole timestamp may [and should] be used. In particular for processes that may span across the days.
3. Below is an example Stata code with comments.

// Set example data
version 15.0
clear all

input str19 starttime str19 endtime
“2018-05-21T01:37:33” “2018-05-21T07:35:57”
end

// Convert to Stata time
generate double startt=clock(subinstr(starttime,“T”," “,1),“YMD hms”)
format startt %tc
generate double endt=clock(subinstr(endtime,“T”,” ",1),“YMD hms”)
format endt %tc

generate double durationh = hours(endt-startt) // in hours
format durationh %8.2f

generate double durationm = minutes(endt-startt) // in minutes
format durationm %8.2f

generate double durations=seconds(endt-startt) // in seconds
format durations %8.2f

// You don’t need to use these to calculate duration, but just in case for endt:
generate byte eh=hh(endt) // hrs of endt
generate byte em=mm(endt) // min of endt
generate byte es=ss(endt) // sec of endt

Thank you Sergiy:)

Dear Sergiy,

I have a similar problem with Tsherin to compute duration of a test.
However, when I copied your Stata command to my Stata version 14, there was a pop-up message saying “too few quotes”.