Main Content

Convert Between Text and datetime or duration Values

This example shows how to convert between text and data types that represent dates and times. The datetime data type represents points in time, such as August 24, 2020, 10:50:30 a.m., and the duration data type represents lengths of time, such as 3 hours, 47 minutes, and 16 seconds. A common reason for converting dates and times to text is to append them to strings that are used as plot labels or file names. Similarly, if a file has columns of data that store dates and times as text, you can read the data from those columns into datetime or duration arrays, making the data more useful for analysis.

To convert:

  • datetime or duration values to text, use the string function. (You can also use the char function to convert these values to character vectors.)

  • text to datetime values, use the datetime function.

  • text to duration values, use the duration function.

Also, some functions, such as the readcell, readvars, and readtable functions, read text from files and automatically convert text representing dates and times to datetime or duration arrays.

Convert datetime and duration Values to Text

Create a datetime value that represents the current date and time.

d = datetime("now")
d = datetime
   31-Aug-2022 03:28:25

To convert d to text, use the string function.

str = string(d)
str = 
"31-Aug-2022 03:28:25"

Similarly, you can convert duration values. For example, first create a duration value that represents 3 hours and 30 minutes. One way to create this value is to use the hours and minutes functions. These functions create duration values that you can then combine.

d = hours(3) + minutes(30)
d = duration
   3.5 hr

Convert d to text.

str = string(d)
str = 
"3.5 hr"

One common use of such strings is to add them to plot labels or file names. For example, create a simple plot with a title that includes today's date. First convert the date and add it to the string myTitle.

d = datetime("today")
d = datetime
   31-Aug-2022

myTitle = "Plot generated on: " + string(d)
myTitle = 
"Plot generated on: 31-Aug-2022"

Create the plot with your title.

plot(rand(10,1))
title(myTitle)

Figure contains an axes object. The axes object with title Plot generated on: 31-Aug-2022 contains an object of type line.

Convert Arrays to String Arrays

You can also convert arrays of datetime or duration values. When you convert them by using the string function, the resulting string array has the same size.

For example, create a datetime array.

D = datetime(2021,1:3,15,12,0,0)'
D = 3x1 datetime
   15-Jan-2021 12:00:00
   15-Feb-2021 12:00:00
   15-Mar-2021 12:00:00

Convert D to a string array.

str = string(D)
str = 3x1 string
    "15-Jan-2021 12:00:00"
    "15-Feb-2021 12:00:00"
    "15-Mar-2021 12:00:00"

Similarly, you can create a duration array and convert it. One way to create a duration array is to use the duration function. Call it with numeric inputs that specify hours, minutes, and seconds.

D = duration(1:3,30,0)'
D = 3x1 duration
   01:30:00
   02:30:00
   03:30:00

Convert the duration array.

str = string(D)
str = 3x1 string
    "01:30:00"
    "02:30:00"
    "03:30:00"

Specify Format of Output Text

The datetime and duration data types have properties that specify the format for display. Live scripts and the Command Window use that format to display values. When you convert datetime or duration arrays by using the string function, you can specify a different format.

For example, create a datetime value and display it.

d = datetime("now")
d = datetime
   31-Aug-2022 03:28:26

Specify a format using letter identifiers for the full name of the month, the day, year, and time. Convert d to a string that represents the date and time using that format.

fmt = "dd MMMM yyyy, hh:mm:ss a";
str = string(d,fmt)
str = 
"31 August 2022, 03:28:26 AM"

Similarly, you can specify a format when you convert a duration array. First create a duration value.

d = hours(1) + minutes(30) + seconds(45)
d = duration
   1.5125 hr

Convert d to a string using the identifiers hh:mm:ss for the hour, minute, and second.

fmt = "hh:mm:ss";
string(d,fmt)
ans = 
"01:30:45"

Note: The string function does not provide a second input argument for a format when converting other data types.

Specify Locale of Output Text

You can also convert datetime and duration arrays using different locales. The locale provides appropriate names for the day and month. To use a locale that is not the default locale, provide it as another input argument.

For example, specify fr_FR as the locale to represent the current date and time using the French name for the month.

d = datetime("now")
d = datetime
   31-Aug-2022 03:28:26

fmt = "dd MMMM yyyy, hh:mm:ss a";
locale = "fr_FR";
str = string(d,fmt,locale)
str = 
"31 août 2022, 03:28:26 AM"

Similarly, you can specify a locale when you convert duration arrays. The locale for France uses a different abbreviation for hours.

d = hours(5)
d = duration
   5 hr

fmt = "h";
locale = "fr_FR";
str = string(d,fmt,locale)
str = 
"5 h"

Note: The string function does not provide a third input argument for a locale when converting other data types.

Convert Text to datetime Values

You can convert text to datetime values if the text specifies dates and times in a format that the datetime function recognizes.

Create a string that represents a date and a time.

str = "2021-09-15 09:12:34"
str = 
"2021-09-15 09:12:34"

Convert str to a datetime value.

d = datetime(str)
d = datetime
   15-Sep-2021 09:12:34

Interpret Format of Input Text

The datetime function recognizes many commonly used text formats. However, if your text is in a format that datetime does not recognize, you can specify the format as an input argument.

For example, create a string that specifies a date and time using the ISO 8601 standard.

str = "2021-09-15T091234"
str = 
"2021-09-15T091234"

The datetime function does not recognize this format. To convert this string to a datetime value, specify the format of the input text. Then call the datetime function. (When the format includes literal text, enclose it in quotation marks. In this example specify the literal text T as 'T'.)

infmt = "yyyy-MM-dd'T'HHmmss";
d = datetime(str,"InputFormat",infmt)
d = datetime
   15-Sep-2021 09:12:34

Convert Text to duration Values

You can convert text to duration values if the text specifies times in a format that the duration function recognizes.

Create a string that represents a length of time.

str = "00:34:01"
str = 
"00:34:01"

Convert str to a duration value.

d = duration(str)
d = duration
   00:34:01

Interpret Format of Input Text

The duration function recognizes formats that specify days, hours, minutes, and seconds separated by colons. These formats are:

  • "dd:hh:mm:ss"

  • "hh:mm:ss"

  • "mm:ss"

  • "hh:mm"

  • Any of the first three formats, with up to nine S characters to indicate fractional second digits, such as "hh:mm:ss.SSSS"

If the input text is ambiguous, which means that it could be interpreted as matching the "mm:ss" or "hh:mm" formats, specify the format as an input argument.

For example, create a string that represents a length of time.

str = "34:01"
str = 
"34:01"

To convert this string to a duration of 34 minutes and 1 second, specify the format. Then call the duration function.

infmt = "mm:ss";
d = duration(str,"InputFormat",infmt)
d = duration
   00:34:01

Read Dates and Times from Files

Many files, such as spreadsheets and text files, store dates and times as text. If the dates and times are in recognized formats, then functions such as readcell, readvars, and readtable can read them and automatically convert them to datetime or duration arrays.

For example, the CSV file outages.csv is a sample file that is distributed with MATLAB®. The file contains data for a set of electrical power outages. The first line of outages.csv has column names. The rest of the file has comma-separated data values for each outage. The file has 1468 lines of data. The first few lines are shown here.

Region,OutageTime,Loss,Customers,RestorationTime,Cause
SouthWest,2002-02-01 12:18,458.9772218,1820159.482,2002-02-07 16:50,winter storm
SouthEast,2003-01-23 00:49,530.1399497,212035.3001,,winter storm
SouthEast,2003-02-07 21:15,289.4035493,142938.6282,2003-02-17 08:14,winter storm
West,2004-04-06 05:44,434.8053524,340371.0338,2004-04-06 06:10,equipment fault
MidWest,2002-03-16 06:18,186.4367788,212754.055,2002-03-18 23:23,severe storm
...

To read the first three columns from outages.csv and store them directly in arrays, use the readvars function. To read text into variables that store string arrays, specify the TextType name-value argument. However, the function recognizes the values in the second column of the CSV file as dates and times and creates the OutageTime variable as a datetime array. Display the first five rows of each output array.

[Region,OutageTime,Loss] = readvars("outages.csv","TextType","string");
whos Region OutageTime Loss
  Name               Size            Bytes  Class       Attributes

  Loss            1468x1             11744  double                
  OutageTime      1468x1             23520  datetime              
  Region          1468x1             83256  string                
Loss(1:5)
ans = 5×1

  458.9772
  530.1399
  289.4035
  434.8054
  186.4368

OutageTime(1:5)
ans = 5x1 datetime
   2002-02-01 12:18
   2003-01-23 00:49
   2003-02-07 21:15
   2004-04-06 05:44
   2002-03-16 06:18

Region(1:5)
ans = 5x1 string
    "SouthWest"
    "SouthEast"
    "SouthEast"
    "West"
    "MidWest"

To read the whole spreadsheet and store the data in a table, use the readtable function. To read text into table variables that store string arrays, specify the TextType name-value argument. However, readtable still converts OutageTime and RestorationTime to table variables that store datetime arrays.

T = readtable("outages.csv","TextType","string")
T=1468×6 table
      Region          OutageTime        Loss     Customers     RestorationTime           Cause      
    ___________    ________________    ______    __________    ________________    _________________

    "SouthWest"    2002-02-01 12:18    458.98    1.8202e+06    2002-02-07 16:50    "winter storm"   
    "SouthEast"    2003-01-23 00:49    530.14    2.1204e+05                 NaT    "winter storm"   
    "SouthEast"    2003-02-07 21:15     289.4    1.4294e+05    2003-02-17 08:14    "winter storm"   
    "West"         2004-04-06 05:44    434.81    3.4037e+05    2004-04-06 06:10    "equipment fault"
    "MidWest"      2002-03-16 06:18    186.44    2.1275e+05    2002-03-18 23:23    "severe storm"   
    "West"         2003-06-18 02:49         0             0    2003-06-18 10:54    "attack"         
    "West"         2004-06-20 14:39    231.29           NaN    2004-06-20 19:16    "equipment fault"
    "West"         2002-06-06 19:28    311.86           NaN    2002-06-07 00:51    "equipment fault"
    "NorthEast"    2003-07-16 16:23    239.93         49434    2003-07-17 01:12    "fire"           
    "MidWest"      2004-09-27 11:09    286.72         66104    2004-09-27 16:37    "equipment fault"
    "SouthEast"    2004-09-05 17:48    73.387         36073    2004-09-05 20:46    "equipment fault"
    "West"         2004-05-21 21:45    159.99           NaN    2004-05-22 04:23    "equipment fault"
    "SouthEast"    2002-09-01 18:22    95.917         36759    2002-09-01 19:12    "severe storm"   
    "SouthEast"    2003-09-27 07:32       NaN    3.5517e+05    2003-10-04 07:02    "severe storm"   
    "West"         2003-11-12 06:12    254.09    9.2429e+05    2003-11-17 02:04    "winter storm"   
    "NorthEast"    2004-09-18 05:54         0             0                 NaT    "equipment fault"
      ⋮

As these table variables are datetime arrays, you can perform convenient calculations with them. For example, you can calculate the durations of the power outages and attach them to the table as a duration array.

T.OutageDuration = T.RestorationTime - T.OutageTime
T=1468×7 table
      Region          OutageTime        Loss     Customers     RestorationTime           Cause          OutageDuration
    ___________    ________________    ______    __________    ________________    _________________    ______________

    "SouthWest"    2002-02-01 12:18    458.98    1.8202e+06    2002-02-07 16:50    "winter storm"         148:32:00   
    "SouthEast"    2003-01-23 00:49    530.14    2.1204e+05                 NaT    "winter storm"               NaN   
    "SouthEast"    2003-02-07 21:15     289.4    1.4294e+05    2003-02-17 08:14    "winter storm"         226:59:00   
    "West"         2004-04-06 05:44    434.81    3.4037e+05    2004-04-06 06:10    "equipment fault"       00:26:00   
    "MidWest"      2002-03-16 06:18    186.44    2.1275e+05    2002-03-18 23:23    "severe storm"          65:05:00   
    "West"         2003-06-18 02:49         0             0    2003-06-18 10:54    "attack"                08:05:00   
    "West"         2004-06-20 14:39    231.29           NaN    2004-06-20 19:16    "equipment fault"       04:37:00   
    "West"         2002-06-06 19:28    311.86           NaN    2002-06-07 00:51    "equipment fault"       05:23:00   
    "NorthEast"    2003-07-16 16:23    239.93         49434    2003-07-17 01:12    "fire"                  08:49:00   
    "MidWest"      2004-09-27 11:09    286.72         66104    2004-09-27 16:37    "equipment fault"       05:28:00   
    "SouthEast"    2004-09-05 17:48    73.387         36073    2004-09-05 20:46    "equipment fault"       02:58:00   
    "West"         2004-05-21 21:45    159.99           NaN    2004-05-22 04:23    "equipment fault"       06:38:00   
    "SouthEast"    2002-09-01 18:22    95.917         36759    2002-09-01 19:12    "severe storm"          00:50:00   
    "SouthEast"    2003-09-27 07:32       NaN    3.5517e+05    2003-10-04 07:02    "severe storm"         167:30:00   
    "West"         2003-11-12 06:12    254.09    9.2429e+05    2003-11-17 02:04    "winter storm"         115:52:00   
    "NorthEast"    2004-09-18 05:54         0             0                 NaT    "equipment fault"            NaN   
      ⋮

See Also

| | | | | | | | | | | |

Related Topics

External Websites