1. What is the best way to convert a time string from CSV in format HH:MM on a 24 hr clock into STATA format?
2. What is the best way to convert date and time in same CSV cell, and generate two different variables "date and time?"
Thanks!
1. What is the best way to convert a time string from CSV in format HH:MM on a 24 hr clock into STATA format?
2. What is the best way to convert date and time in same CSV cell, and generate two different variables "date and time?"
Thanks!
Great questions! We will cover dates in depth next week and the process to convert time is very similar in STATA. The dates mini lecture and sample do file are posted to the CLE if you would like to work through an example.
1. What is the best way to convert a time string from CSV in format HH:MM on a 24 hr clock into STATA format?
- First generate a new time variable using the following syntax:
gen timenew = clock(time,"hm",)
In this example "timenew" is the name of the new numeric variable for time you are creating, "clock" is the command to convert the string to a numeric value, "time" is the original string variable for time, and "hm" specifies hours and minutes.
- Second, you will need to change the new time variable (timenew) into an understandable format. Use the following command:
format timenew %tcHH:MM
You will now have a numeric variable with time in the format of HH:MM
2. What is the best way to convert date and time in same CSV cell, and generate two different variables "date and time?"
If you have date and time in the same cell, you can extract components of one cell into separate columns.
-First you need to convert the variable from a string variable to a numeric variable as detailed in the first question.
- Second you will use the dofc and cofd commands to create new different variables for date and time. For example:
gen datetimenew = clock(datetime, "MDY hm")
format datetimenew %tcNN/DD/CCYY_HH:MM
gen date = dofc(datetimenew)
format date %td
gen double time = cofd(datetimenew)
format time %tc