3
votes

I have one question. How to convert that format 20110711201023 of date and time, to the number of hours. This is output of software which I use to image analysis, and I can’t change it. It is very important to define starting Date and Time. Format: 2011 year, 07 month, 11 day, 20 hour, 10 minute, 23 second. Example:

Starting Data and Time - 20110709201023,
First Data and Time - 20110711214020
Result = 49,5h.

I have 10000 data in this format so I don't want to do this manually. I will be very gratefully for any advice.

1

1 Answers

3
votes

Best is to first make it a real R time object using strptime:

time_obj = strptime("20110711201023", format = "%Y%m%d%H%M%S")

If you do this with both the start and the end date, you can simply say:

end_time - start_time 

to get the difference in seconds, which can easily be converted to number of hours. To convert a whole list of these time strings, simply do:

time_vector = strptime(dat$time_string, format = "%Y%m%d%H%M%S")

where dat is the data.frame with the data, and time_string the column containing the time strings. Note that strptime works also on a vector (it is vectorized). You can also make the new time vector part of dat:

dat$time = strptime(dat$time_string, format = "%Y%m%d%H%M%S")

or more elegantly (at least if you hate $ as much as me :)):

dat = within(dat, { time = strptime(dat$time_string, format = "%Y%m%d%H%M%S") })