Datetime — Date and time values and variables 5
Examples:
1. You have datetimes stored in the string variable mystr, an example being 2010.07.12
14:32. To convert this to a Stata datetime/c variable, you type
. generate double eventtime = clock(mystr, "YMDhm")
The string contains the year, month, and day followed by the hour and minute, so you
specify the mask "YMDhm".
2. You have datetimes stored in mystr, an example being 2010.07.12 14:32:12. You type
. generate double eventtime = clock(mystr, "YMDhms")
Mask element s specifies seconds. In example 1, there were no seconds; in this example,
there are.
3. You have datetimes stored in mystr, an example being 2010 Jul 12 14:32. You type
. generate double eventtime = clock(mystr, "YMDhm")
This is the same command that you typed in example 1. In the mask, you specify the order
of the components; Stata figures out the style for itself. In example 1, months were numeric.
In this example, they are spelled out (and happen to be abbreviated).
4. You have datetimes stored in mystr, an example being July 12, 2010 2:32 PM. You type
. generate double eventtime = clock(mystr, "MDYhm")
Stata automatically looks for AM and PM, in uppercase and lowercase, with and without
periods.
5. You have datetimes stored in mystr, an example being 7-12-10 14.32. The 2-digit year
is to be interpreted as being prefixed with 20. You type
. generate double eventtime = clock(mystr, "MD20Yhm")
6. You have datetimes stored in mystr, an example being 14:32 on 7/12/2010. You type
. generate double eventtime = clock(mystr, "hm#MDY")
The # sign between m and M means “ignore one thing between minute and month”, which
in this case is the word “on”. Had you omitted the # from the mask, the new variable
eventtime would have contained missing values.
7. You have a date stored in mystr, an example being 22/7/2010. In this case, you want to
create a Stata date instead of a datetime. You type
. generate eventdate = date(mystr, "DMY")
Typing
. generate double eventtime = clock(mystr, "DMY")
would have worked, too. Variable eventtime would contain a different coding from that
contained by eventdate; namely, it would contain milliseconds from 1jan1960 rather than
days (1,595,376,000,000 rather than 18,465). Datetime value 1,595,376,000,000 corresponds
to 22jul2010 00:00:00.000.