Main Content

Combine Date and Time from Separate Variables

This example shows how to read date and time data from a text file. Then, it shows how to combine date and time information stored in separate variables into a single datetime variable.

Create a space-delimited text file named schedule.txt that contains the following (to create the file, use any text editor, and copy and paste):

Date Name Time
10.03.2015 Joe 14:31
10.03.2015 Bob 15:33
11.03.2015 Bob 11:29
12.03.2015 Kim 12:09
12.03.2015 Joe 13:05

Read the file using the readtable function. Use the %D conversion specifier to read the first and third columns of data as datetime values.

T = readtable('schedule.txt','Format','%{dd.MM.uuuu}D %s %{HH:mm}D','Delimiter',' ')
T = 
       Date       Name     Time 
    __________    _____    _____
    10.03.2015    'Joe'    14:31
    10.03.2015    'Bob'    15:33
    11.03.2015    'Bob'    11:29
    12.03.2015    'Kim'    12:09
    12.03.2015    'Joe'    13:05

readtable returns a table containing three variables.

Change the display format for the T.Date and T.Time variables to view both date and time information. Since the data in the first column of the file ("Date") have no time information, the time of the resulting datetime values in T.Date default to midnight. Since the data in the third column of the file ("Time") have no associated date, the date of the datetime values in T.Time defaults to the current date.

T.Date.Format = 'dd.MM.uuuu HH:mm';
T.Time.Format = 'dd.MM.uuuu HH:mm';
T
T = 
          Date          Name           Time      
    ________________    _____    ________________
    10.03.2015 00:00    'Joe'    12.12.2014 14:31
    10.03.2015 00:00    'Bob'    12.12.2014 15:33
    11.03.2015 00:00    'Bob'    12.12.2014 11:29
    12.03.2015 00:00    'Kim'    12.12.2014 12:09
    12.03.2015 00:00    'Joe'    12.12.2014 13:05

Combine the date and time information from two different table variables by adding T.Date and the time values in T.Time. Extract the time information from T.Time using the timeofday function.

myDatetime = T.Date + timeofday(T.Time)
myDatetime = 
   10.03.2015 14:31
   10.03.2015 15:33
   11.03.2015 11:29
   12.03.2015 12:09
   12.03.2015 13:05

See Also

|