Statalist The Stata Listserver


[Date Prev][Date Next][Thread Prev][Thread Next][Date index][Thread index]

st: Program for timestamp conversion


From   "Tobias Pfaff" <[email protected]>
To   <[email protected]>
Subject   st: Program for timestamp conversion
Date   Mon, 26 Feb 2007 00:15:45 +0100

Hi!
 
I had the problem to convert timestamps in milliseconds generated by a
server to an appropriate Stata format. As Stata calculates the date format
in days from 1/1/1960 and the timestamp is calculated in ms from 1/1/1970
some conversions were necessary. This is handled by the following program.
The program uses the function _tod()_ which is contained in the
egenmore-package (type 'ssc install egenmore'). 
 
This is the program (convert_ms.ado):

-------------------------------------
 
** PROGRAM TO CONVERT TIMESTAMP IN MILLISECONDS TO ORDINARY DATE FORMAT

*! version 1.0.0 25feb2007

capture program drop convert_ms
program define convert_ms

version 9

syntax varname

* CALCULATE DAYS FROM MILLISECONDS
gen double time_days = (`varlist'/1000/60/60/24)

* GENERATE DATE VARIABLE BY ADDING SPREAD BETWEEN 1/1/1960 (STATA) AND
1/1/1970 (SERVER TIMESTAMP)
gen date = time_days + mdy(1,1,1970)
format date %dN/D/CY

* CALCULATE HOURS, MINUTES, AND SECONDS
gen double temp_seconds = round((mod(time_days,1))*24*60*60)
egen time_seconds = tod(temp_seconds)

* COMBINE DATE AND TIME TO ONE STRING
gen temp_date = string(date, "%dN/D/CY")

egen `varlist'_converted = concat(temp_date time_seconds), punct(" ")

* DROP TEMPORARY VARIABLES AND BRING VARIABLES TO ORDER
drop time_days date temp_seconds time_seconds temp_date 
move `varlist'_converted `varlist' 

end

-------------------------

In the do-file where I prepare the data, 'do convert_ms.ado' has to be
called. Afterwards, the function _convert_ms_ can be used (e.g. 'convert_ms
timestamp_variable').

Hope this helps somebody. 

Cheers,
Tobias Pfaff

University of Muenster
Germany

*
*   For searches and help try:
*   http://www.stata.com/support/faqs/res/findit.html
*   http://www.stata.com/support/statalist/faq
*   http://www.ats.ucla.edu/stat/stata/



© Copyright 1996–2024 StataCorp LLC   |   Terms of use   |   Privacy   |   Contact us   |   What's new   |   Site index