Search code examples
stata

Generating a Stata date variable from ISO datetime string


I have datetime strings that look like this:

starttime = 2017-01-03T00:00:00.000000-05:00

I would like to generate Stata datetime variables from that sting, but am having difficulty. This is the code I am using:

generate stataDate = clock(starttime, "YMD!THH:MM:SS")

Do you know the correct mast to use with this string? I have been looking through the documentation but cannot find an answer.


Solution

  • The following may point you in a useful direction.

    clear
    input str32 starttime
    "2017-01-03T00:00:00.000000-05:00"
    "2017-01-03T12:34:56.654321-05:00"
    end
    generate double sd = clock(starttime,"YMD#hms##")
    format sd %tcCCYY-NN-DD_HH:MM:SS.sss
    

    which yields

    . list, clean
    
                                  starttime                        sd  
      1.   2017-01-03T00:00:00.000000-05:00   2017-01-03 00:00:00.000  
      2.   2017-01-03T12:34:56.654321-05:00   2017-01-03 12:34:56.654  
    

    Worth noting is that the limit on precision for Stata datetime values is milliseconds: those are the units in which the values are stored. Also crucial is that datetime values must be stored as a double numeric value rather than a float, which cannot retain full accuracy.

    Stata's date and time variables are complicated and there is a lot to learn. If you have not already read the very detailed Chapter 24 (Working with dates and times) of the Stata User's Guide PDF, do so now. If you have, it's time for a refresher. After that, the help datetime documentation will usually be enough to point the way. You can't remember everything; even the most experienced users end up referring to the help datetime documentation or back to the manual for details. But at least you will get a good understanding of the basics and the underlying principles. An investment of time that will be amply repaid.