Date variables
Note
If you do not work with date variables, you might skip this subchapter.
Date variables
// See the pdf on date variables for an overview
* Convert strings into dates
clear
set obs 10
gen date_str = "15. April 2021" // most time variables are imported as strings
gen date = date(date_str,"DMY") // transform them with the date() function
br // Stata stores dates as days since 01 Jan 1960
* Date format
format date %td // format to make it human-readable
format date %tdDD_Month_YY // many ways how to format date variables
help datetime_display_formats
* Convert strings into dates based on different formats
gen tomorrow1 = date("16. April 2021","DMY") // "DMY": date is given as day, month, year
gen tomorrow2 = date("April 16, 2021","MDY") // "MDY": date is given as month, day, year
gen tomorrow3 = td(16apr2021) // transform "formatted" string into date
format tomorrow1 tomorrow2 tomorrow3 %td
br
* Display dates
display date("April 16, 2021","MDY")
display %td date("April 16, 2021","MDY")
* Calculate with dates
drop tomorrow*
gen tomorrow = date+1 // dates are numeric --> normal calculation possible
gen yesterday = date-1
format tomorrow yesterday %td // remember to format date variables
help datetime durations // special date functions for durations
gen birth = date("20. November 2011","DMY")
gen age = age(birth,date)
* Extract dates
gen year = year(date) // get year from date variable
gen month = month(date) // get month from date variable
gen day = day(date) // get day (in month) from date variable
br date year-day
* Combine dates
gen new_date = mdy(month,day,year) // get date from components
format new_date %td
* Common mistake
gen time = clock("15. April 2021 12:00:00","DMYhms")
format time %tc
br time
help data_types
su time
gen double exact_time = clock("15. April 2021 12:00:00","DMYhms")
format exact_time %tc
br *time
Helpful PDF file
Exercise
Remark: Check the pdf-file for helpful functions.
Clear your working space. Set the number of observations to 12.
- Generate a variable called “day” containing 1’s. Generate a variable called “month” containing the numbers 1-12 (hint: you can use a system variable for this). Generate a variable called “year” containing the number 2021. Combine the three variables to generate a date variable. Format the date variable accordingly.
- Generate a variable which indicates the day of the week of the dates obtained from (1).
- Generate a string variable which contains today’s date and the current time (use the date notation you prefer). Based on this variable, generate a time variable. Format the variable accordingly.
- Advanced: Generate a copy of the variable from (3), and format it such that only the hour and the minute is displayed (with a colon between hour and minute). Use the command tostring to generate a string variable containing the time. Hint: check the different options of tostring.