{"id":1109,"date":"2015-03-11T07:24:45","date_gmt":"2015-03-11T12:24:45","guid":{"rendered":"https:\/\/blogs.mathworks.com\/loren\/?p=1109"},"modified":"2015-02-11T07:25:22","modified_gmt":"2015-02-11T12:25:22","slug":"matlab-data-types-for-dates-and-time-part-ii","status":"publish","type":"post","link":"https:\/\/blogs.mathworks.com\/loren\/2015\/03\/11\/matlab-data-types-for-dates-and-time-part-ii\/","title":{"rendered":"MATLAB Data Types for Dates and Time, Part II"},"content":{"rendered":"\r\n<div class=\"content\"><!--introduction--><p>Once again we're going to hear from guest blogger Andrea Ho, who works for the MATLAB Documentation team here at MathWorks.<\/p><!--\/introduction--><h3>Contents<\/h3><div><ul><li><a href=\"#2115364c-af89-45e6-8af7-20a9421cc26c\">Interest Payments from a Swiss Bank<\/a><\/li><li><a href=\"#451c0eb8-cbaa-4917-94be-1613c4b498f0\">Not Every Day Has 24 Hours<\/a><\/li><li><a href=\"#1c87cda7-034f-482c-bfb5-4f78e9f50f9f\">Quarterly Statistics<\/a><\/li><li><a href=\"#899d090e-56fd-43ce-979a-d8c39a9b2203\">Convert Date Numbers to Datetime<\/a><\/li><li><a href=\"#29b29667-2d38-45f1-a370-e0d3d7735e21\">Your Thoughts?<\/a><\/li><\/ul><\/div><p><a href=\"https:\/\/blogs.mathworks.com\/loren\/2015\/02\/12\/introduction-to-the-new-matlab-data-types-for-dates-and-time\/\">Last time<\/a>, I introduced new data types for representing date and time data in MATLAB: <a href=\"https:\/\/www.mathworks.com\/help\/matlab\/ref\/datetime.html\"><tt>datetime<\/tt><\/a> for representing specific points in time, <a href=\"https:\/\/www.mathworks.com\/help\/matlab\/ref\/duration.html\"><tt>duration<\/tt><\/a> for representing exact differences between points in time, and <a href=\"https:\/\/www.mathworks.com\/help\/matlab\/ref\/calendarduration.html\"><tt>calendarDuration<\/tt><\/a> for representing flexible amounts of time such as months. Today, we'll look at how these data types help you to work with time zones, daylight saving time, and dates in languages other than English.<\/p><h4>Interest Payments from a Swiss Bank<a name=\"2115364c-af89-45e6-8af7-20a9421cc26c\"><\/a><\/h4><p>Last time, we looked at bank interest payments over the course of a year, without paying attention to the bank location. Let's do a similar analysis, but this time, our bank is located in Switzerland and we are in Phoenix, Arizona.<\/p><p>Suppose we opened a bank account on January 1, 2013, and the account pays interest monthly on the last day of each month. Create a sequence of dates in 2013 to represent when the bank account pays interest. The <a href=\"https:\/\/www.mathworks.com\/help\/matlab\/ref\/dateshift.html\"><tt>dateshift<\/tt><\/a> function can shift a date <i>and<\/i> create a sequence based on the initial date in one line.<\/p><pre class=\"codeinput\">p0 = datetime(2013,1,1);\r\np = dateshift(p0,<span class=\"string\">'end'<\/span>,<span class=\"string\">'month'<\/span>,0:11)'\r\n<\/pre><pre class=\"codeoutput\">p = \r\n   31-Jan-2013\r\n   28-Feb-2013\r\n   31-Mar-2013\r\n   30-Apr-2013\r\n   31-May-2013\r\n   30-Jun-2013\r\n   31-Jul-2013\r\n   31-Aug-2013\r\n   30-Sep-2013\r\n   31-Oct-2013\r\n   30-Nov-2013\r\n   31-Dec-2013\r\n<\/pre><p>Suppose our records indicate that we received interest payments at either 3 AM or 4 AM, depending on the month of the year. We can input this information to our <tt>datetime<\/tt> vector <tt>p<\/tt>, by modifying its <tt>Hour<\/tt> property.<\/p><pre class=\"codeinput\">p.Hour = [4 4 3 3 3 3 3 3 3 4 4 4]';\r\np.Format = <span class=\"string\">'dd-MMM-yyyy HH:mm'<\/span>\r\n<\/pre><pre class=\"codeoutput\">p = \r\n   31-Jan-2013 04:00\r\n   28-Feb-2013 04:00\r\n   31-Mar-2013 03:00\r\n   30-Apr-2013 03:00\r\n   31-May-2013 03:00\r\n   30-Jun-2013 03:00\r\n   31-Jul-2013 03:00\r\n   31-Aug-2013 03:00\r\n   30-Sep-2013 03:00\r\n   31-Oct-2013 04:00\r\n   30-Nov-2013 04:00\r\n   31-Dec-2013 04:00\r\n<\/pre><p>Our bank in Zurich, Switzerland, has sent us a file named <tt>interest_2013.txt<\/tt> that contains interest amounts for each month of the year.<\/p><p>For English-language dates and times, you can use the <a href=\"\">Import Tool<\/a> to import your data graphically. However, the dates in our file are written in German:<\/p><pre>Date,Interest\r\n31. Januar 2013 12:00,1.93\r\n28. Februar 2013 12:00,4.28\r\n31. M&auml;rz 2013 12:00,4.82\r\n30. April 2013 12:00,1.23\r\n31. Mai 2013 12:00,5.89\r\n30. Juni 2013 12:00,2.26\r\n31. Juli 2013 12:00,3.84\r\n31. August 2013 12:00,5.82\r\n30. September 2013 12:00,2.51\r\n31. Oktober 2013 12:00,2.99\r\n30. November 2013 12:00,6.17\r\n31. Dezember 2013 12:00,2.65<\/pre><p>For non-English language dates, we must import the data using functions. We will use <a href=\"https:\/\/www.mathworks.com\/help\/matlab\/ref\/readtable.html\"><tt>readtable<\/tt><\/a> to read the file data into a table. Use the <tt>%D<\/tt> specifier to read the first column of data as <tt>datetime<\/tt> values and specify the format of the date strings within curly braces. The <tt>'DateLocale'<\/tt> name-value pair argument tells MATLAB how to interpret the date strings in the file. The value of <tt>DateLocale<\/tt> is a combination of a lowercase <a href=\"http:\/\/en.wikipedia.org\/wiki\/List_of_ISO_639-1_codes\">language code<\/a> and an uppercase <a href=\"http:\/\/en.wikipedia.org\/wiki\/ISO_3166-1_alpha-2\">country code<\/a>. For example, <tt>'de_CH'<\/tt> indicates German-language dates in Switzerland.<\/p><pre class=\"codeinput\">T = readtable(<span class=\"string\">'interest_2013.txt'<\/span>,<span class=\"keyword\">...<\/span>\r\n    <span class=\"string\">'Format'<\/span>,<span class=\"string\">'%{dd.MMMM yyyy HH:mm}D %f'<\/span>,<span class=\"string\">'DateLocale'<\/span>,<span class=\"string\">'de_CH'<\/span>)\r\n<\/pre><pre class=\"codeoutput\">T = \r\n             Date              Interest\r\n    _______________________    ________\r\n    31.January 2013 12:00      1.93    \r\n    28.February 2013 12:00     4.28    \r\n    31.March 2013 12:00        4.82    \r\n    30.April 2013 12:00        1.23    \r\n    31.May 2013 12:00          5.89    \r\n    30.June 2013 12:00         2.26    \r\n    31.July 2013 12:00         3.84    \r\n    31.August 2013 12:00       5.82    \r\n    30.September 2013 12:00    2.51    \r\n    31.October 2013 12:00      2.99    \r\n    30.November 2013 12:00     6.17    \r\n    31.December 2013 12:00     2.65    \r\n<\/pre><p>It appears that the bank's payments were made at noon each month, while our own records indicate otherwise. What happened? Our original times are based in Phoenix, whereas the imported times from the bank are based in Zurich.<\/p><p>By default, <tt>datetime<\/tt> values are not associated with any time zone. That is, they are \"unzoned\". Because we want to compare dates and times across geographic locations and therefore time zones, we should associate each <tt>datetime<\/tt> array with a time zone. You can learn more about time zones <a href=\"https:\/\/www.mathworks.com\/help\/matlab\/matlab_prog\/specify-time-zones.html\">here<\/a>.<\/p><p>Let's set the time zone for our Phoenix-based <tt>datetime<\/tt> vector, <tt>p<\/tt>. Valid values for the <tt>TimeZone<\/tt> property include names of time zone regions from the <a href=\"http:\/\/www.iana.org\/time-zones\">IANA Time Zone Database<\/a>.  Then, adjust the display format to show the UTC offset for each value.<\/p><pre class=\"codeinput\">p.TimeZone = <span class=\"string\">'America\/Phoenix'<\/span>;\r\np.Format = <span class=\"string\">'dd-MMM-yyyy HH:mm Z'<\/span>\r\n<\/pre><pre class=\"codeoutput\">p = \r\n   31-Jan-2013 04:00 -0700\r\n   28-Feb-2013 04:00 -0700\r\n   31-Mar-2013 03:00 -0700\r\n   30-Apr-2013 03:00 -0700\r\n   31-May-2013 03:00 -0700\r\n   30-Jun-2013 03:00 -0700\r\n   31-Jul-2013 03:00 -0700\r\n   31-Aug-2013 03:00 -0700\r\n   30-Sep-2013 03:00 -0700\r\n   31-Oct-2013 04:00 -0700\r\n   30-Nov-2013 04:00 -0700\r\n   31-Dec-2013 04:00 -0700\r\n<\/pre><p>Unlike most of the United States, Phoenix does not observe daylight saving time and is always 7 hours behind UTC.<\/p><p>Now, specify that the bank's payment times are in Zurich's time zone.<\/p><pre class=\"codeinput\">z = T.Date;\r\nz.TimeZone = <span class=\"string\">'Europe\/Zurich'<\/span>;\r\nz.Format = <span class=\"string\">'dd-MMM-yyyy HH:mm Z'<\/span>\r\n<\/pre><pre class=\"codeoutput\">z = \r\n   31-Jan-2013 12:00 +0100\r\n   28-Feb-2013 12:00 +0100\r\n   31-Mar-2013 12:00 +0200\r\n   30-Apr-2013 12:00 +0200\r\n   31-May-2013 12:00 +0200\r\n   30-Jun-2013 12:00 +0200\r\n   31-Jul-2013 12:00 +0200\r\n   31-Aug-2013 12:00 +0200\r\n   30-Sep-2013 12:00 +0200\r\n   31-Oct-2013 12:00 +0100\r\n   30-Nov-2013 12:00 +0100\r\n   31-Dec-2013 12:00 +0100\r\n<\/pre><p>In Zurich, the time zone offset changes during the year because Zurich observes daylight saving time.<\/p><p>Now if we compare our payment times with the bank's data, we'll see that they are the same.<\/p><pre class=\"codeinput\">isequal(p,z)\r\n<\/pre><pre class=\"codeoutput\">ans =\r\n     1\r\n<\/pre><h4>Not Every Day Has 24 Hours<a name=\"451c0eb8-cbaa-4917-94be-1613c4b498f0\"><\/a><\/h4><p>On what day of the week were interest payments made? We can use the <a href=\"https:\/\/www.mathworks.com\/help\/matlab\/ref\/day.html\"><tt>day<\/tt><\/a> function to extract the day name from each value in <tt>z<\/tt>.<\/p><pre class=\"codeinput\">d = day(z,<span class=\"string\">'name'<\/span>)\r\n<\/pre><pre class=\"codeoutput\">d = \r\n    'Thursday'\r\n    'Thursday'\r\n    'Sunday'\r\n    'Tuesday'\r\n    'Friday'\r\n    'Sunday'\r\n    'Wednesday'\r\n    'Saturday'\r\n    'Monday'\r\n    'Thursday'\r\n    'Saturday'\r\n    'Tuesday'\r\n<\/pre><p>The third payment date (March 31) falls on a Sunday. Suppose the bank shifted this payment date earlier by two days so that it would not fall on a weekend.<\/p><p>What happens if we subtract a <tt>duration<\/tt> of 2 standard, 24-hour long days to the corresponding payment date?<\/p><pre class=\"codeinput\">new_date = z(3) - days(2)\r\n<\/pre><pre class=\"codeoutput\">new_date = \r\n   29-Mar-2013 11:00 +0100\r\n<\/pre><p>Notice that the new payment time is now 11 AM instead of noon because a daylight saving time shift occurred in Zurich on March 30, 2014.<\/p><p>To account for a daylight saving time shift in a calendar calculation, we should subtract 2 <i>calendar days<\/i> from the original payment date.<\/p><pre class=\"codeinput\">new_date = z(3) - caldays(2)\r\n<\/pre><pre class=\"codeoutput\">new_date = \r\n   29-Mar-2013 12:00 +0100\r\n<\/pre><p>Now the payment time is at noon, and is consistent with the payment times during the rest of the year. If we calculate the exact <i>duration<\/i> between the original payment date and the new payment date, we will see that the difference is not 48 hours (two 24-hour long days). Rather, the difference is 47 hours due to the daylight saving time change.<\/p><pre class=\"codeinput\">new_date - z(3)\r\n<\/pre><pre class=\"codeoutput\">ans = \r\n   -47:00:00\r\n<\/pre><p>Here's the big takeaway: When a <tt>datetime<\/tt> value is associated with a time zone that observes daylight saving time, it is affected by daylight saving time changes. To correctly account for such time changes, make sure you use <i>calendar durations<\/i> instead of durations in calendar calculations involving days, months, or years. <tt>calendarDuration<\/tt> values account for non-constant lengths of time such as the length of a day, which is not always equal to 24 hours in some time zones.<\/p><h4>Quarterly Statistics<a name=\"1c87cda7-034f-482c-bfb5-4f78e9f50f9f\"><\/a><\/h4><p>Now we will calculate the mean of the interest payments for each quarter. Just like how the <tt>day<\/tt> function can extract day names for each <tt>datetime<\/tt> value in an array, the <a href=\"https:\/\/www.mathworks.com\/help\/matlab\/ref\/quarter.html\"><tt>quarter<\/tt><\/a> function lets us extract the quarter number.<\/p><pre class=\"codeinput\">q = quarter(z)\r\n<\/pre><pre class=\"codeoutput\">q =\r\n     1\r\n     1\r\n     1\r\n     2\r\n     2\r\n     2\r\n     3\r\n     3\r\n     3\r\n     4\r\n     4\r\n     4\r\n<\/pre><p>Now we can calculate statistics for the interest payments associated with each unique value of of <tt>q<\/tt>.<\/p><pre class=\"codeinput\"><span class=\"keyword\">for<\/span> ii = 1:4\r\n    X = sprintf(<span class=\"string\">'Quarter %d'<\/span>,ii);\r\n    disp(X)\r\n    tf = q==ii;\r\n    m_quarter = mean(T.Interest(tf))\r\n    <span class=\"comment\">% T.Interest is a column containing interest values from<\/span>\r\n    <span class=\"comment\">% the text file we imported earlier<\/span>\r\n<span class=\"keyword\">end<\/span>\r\n<\/pre><pre class=\"codeoutput\">Quarter 1\r\nm_quarter =\r\n       3.6767\r\nQuarter 2\r\nm_quarter =\r\n       3.1267\r\nQuarter 3\r\nm_quarter =\r\n       4.0567\r\nQuarter 4\r\nm_quarter =\r\n       3.9367\r\n<\/pre><h4>Convert Date Numbers to Datetime<a name=\"899d090e-56fd-43ce-979a-d8c39a9b2203\"><\/a><\/h4><p>Now we've seen how to create <tt>datetime<\/tt> values and how to import date and time data as <tt>datetime<\/tt> values that can account for time zones and daylight saving time. But what if you currently have data in the form of serial date numbers? Fear not, there's an easy way to convert your existing data to more convenient datetime values. Let's start with an array of serial date numbers:<\/p><pre class=\"codeinput\">dn = (735600:31:735755)'\r\n<\/pre><pre class=\"codeoutput\">dn =\r\n      735600\r\n      735631\r\n      735662\r\n      735693\r\n      735724\r\n      735755\r\n<\/pre><p>Use the <tt>datetime<\/tt> function to easily convert the date numbers to datetime values.<\/p><pre class=\"codeinput\">p = datetime(dn,<span class=\"string\">'ConvertFrom'<\/span>,<span class=\"string\">'datenum'<\/span>)\r\n<\/pre><pre class=\"codeoutput\">p = \r\n   01-Jan-2014 00:00:00\r\n   01-Feb-2014 00:00:00\r\n   04-Mar-2014 00:00:00\r\n   04-Apr-2014 00:00:00\r\n   05-May-2014 00:00:00\r\n   05-Jun-2014 00:00:00\r\n<\/pre><p>An array of serial date numbers cannot account for a time zone, but you can add time zone information to the <tt>datetime<\/tt> array.<\/p><pre class=\"codeinput\">p.TimeZone = <span class=\"string\">'America\/New_York'<\/span>;\r\n<\/pre><p>You can even export the <tt>datetime<\/tt> array in a different language. Let's translate the dates into German and then export them to a text file.<\/p><pre class=\"codeinput\">C = cellstr(p,<span class=\"string\">'dd. MMMM yyyy'<\/span>,<span class=\"string\">'de_DE'<\/span>)\r\n<\/pre><pre class=\"codeoutput\">C = \r\n    '01. Januar 2014'\r\n    '01. Februar 2014'\r\n    '04. M&auml;rz 2014'\r\n    '04. April 2014'\r\n    '05. Mai 2014'\r\n    '05. Juni 2014'\r\n<\/pre><pre class=\"codeinput\">T  = table(C,rand(6,1),<span class=\"string\">'VariableNames'<\/span>,{<span class=\"string\">'Date'<\/span>,<span class=\"string\">'InterestRate'<\/span>})\r\n<\/pre><pre class=\"codeoutput\">T = \r\n           Date           InterestRate\r\n    __________________    ____________\r\n    '01. Januar 2014'      0.2785     \r\n    '01. Februar 2014'    0.54688     \r\n    '04. M&auml;rz 2014'       0.95751     \r\n    '04. April 2014'      0.96489     \r\n    '05. Mai 2014'        0.15761     \r\n    '05. Juni 2014'       0.97059     \r\n<\/pre><pre class=\"codeinput\">writetable(T,<span class=\"string\">'myfile.txt'<\/span>)\r\n<\/pre><h4>Your Thoughts?<a name=\"29b29667-2d38-45f1-a370-e0d3d7735e21\"><\/a><\/h4><p>Have you tried using the <tt>datetime<\/tt>, <tt>duration<\/tt>, and <tt>calendarDuration<\/tt> data types? Let us know what you think by leaving a comment <a href=\"https:\/\/blogs.mathworks.com\/loren\/?p=1109#respond\">here<\/a>.<\/p><script language=\"JavaScript\"> <!-- \r\n    function grabCode_1b37a49dfdb84f569bbd8cb54aa6fb0b() {\r\n        \/\/ Remember the title so we can use it in the new page\r\n        title = document.title;\r\n\r\n        \/\/ Break up these strings so that their presence\r\n        \/\/ in the Javascript doesn't mess up the search for\r\n        \/\/ the MATLAB code.\r\n        t1='1b37a49dfdb84f569bbd8cb54aa6fb0b ' + '##### ' + 'SOURCE BEGIN' + ' #####';\r\n        t2='##### ' + 'SOURCE END' + ' #####' + ' 1b37a49dfdb84f569bbd8cb54aa6fb0b';\r\n    \r\n        b=document.getElementsByTagName('body')[0];\r\n        i1=b.innerHTML.indexOf(t1)+t1.length;\r\n        i2=b.innerHTML.indexOf(t2);\r\n \r\n        code_string = b.innerHTML.substring(i1, i2);\r\n        code_string = code_string.replace(\/REPLACE_WITH_DASH_DASH\/g,'--');\r\n\r\n        \/\/ Use \/x3C\/g instead of the less-than character to avoid errors \r\n        \/\/ in the XML parser.\r\n        \/\/ Use '\\x26#60;' instead of '<' so that the XML parser\r\n        \/\/ doesn't go ahead and substitute the less-than character. \r\n        code_string = code_string.replace(\/\\x3C\/g, '\\x26#60;');\r\n\r\n        copyright = 'Copyright 2015 The MathWorks, Inc.';\r\n\r\n        w = window.open();\r\n        d = w.document;\r\n        d.write('<pre>\\n');\r\n        d.write(code_string);\r\n\r\n        \/\/ Add copyright line at the bottom if specified.\r\n        if (copyright.length > 0) {\r\n            d.writeln('');\r\n            d.writeln('%%');\r\n            if (copyright.length > 0) {\r\n                d.writeln('% _' + copyright + '_');\r\n            }\r\n        }\r\n\r\n        d.write('<\/pre>\\n');\r\n\r\n        d.title = title + ' (MATLAB code)';\r\n        d.close();\r\n    }   \r\n     --> <\/script><p style=\"text-align: right; font-size: xx-small; font-weight:lighter;   font-style: italic; color: gray\"><br><a href=\"javascript:grabCode_1b37a49dfdb84f569bbd8cb54aa6fb0b()\"><span style=\"font-size: x-small;        font-style: italic;\">Get \r\n      the MATLAB code <noscript>(requires JavaScript)<\/noscript><\/span><\/a><br><br>\r\n      Published with MATLAB&reg; R2014b<br><\/p><\/div><!--\r\n1b37a49dfdb84f569bbd8cb54aa6fb0b ##### SOURCE BEGIN #####\r\n%% MATLAB Data Types for Dates and Time, Part II\r\n% Once again we're going to hear from guest blogger Andrea Ho, who works\r\n% for the MATLAB Documentation team here at MathWorks.\r\n%%\r\n% <https:\/\/blogs.mathworks.com\/loren\/2015\/02\/12\/introduction-to-the-new-matlab-data-types-for-dates-and-time\/\r\n% Last time>, I introduced new data types for representing date and time\r\n% data in MATLAB: <https:\/\/www.mathworks.com\/help\/matlab\/ref\/datetime.html\r\n% |datetime|> for representing specific points in time,\r\n% <https:\/\/www.mathworks.com\/help\/matlab\/ref\/duration.html |duration|> for\r\n% representing exact differences between points in time, and\r\n% <https:\/\/www.mathworks.com\/help\/matlab\/ref\/calendarduration.html\r\n% |calendarDuration|> for representing flexible amounts of time such as\r\n% months. Today, we'll look at how these data types help you to work with\r\n% time zones, daylight saving time, and dates in languages other than\r\n% English.\r\n%% Interest Payments from a Swiss Bank\r\n% Last time, we looked at bank interest payments over the course of a year,\r\n% without paying attention to the bank location. Let's\r\n% do a similar analysis, but this time, our bank\r\n% is located in Switzerland and we are in Phoenix, Arizona. \r\n%%\r\n% Suppose we opened a bank account on January 1, 2013, and the account pays\r\n% interest monthly on the last day of each month.\r\n% Create a sequence of dates in 2013 to represent when the bank account\r\n% pays interest. The\r\n% <https:\/\/www.mathworks.com\/help\/matlab\/ref\/dateshift.html |dateshift|>\r\n% function can shift a date _and_ create a sequence based on the\r\n% initial date in one line.\r\np0 = datetime(2013,1,1);\r\np = dateshift(p0,'end','month',0:11)' \r\n\r\n%%\r\n% Suppose our records indicate that we received interest payments at either\r\n% 3 AM or 4 AM, depending on the month of the year. We can input this\r\n% information to our |datetime| vector |p|, by modifying its |Hour| property.\r\np.Hour = [4 4 3 3 3 3 3 3 3 4 4 4]';\r\np.Format = 'dd-MMM-yyyy HH:mm'\r\n%%\r\n% Our bank in Zurich, Switzerland, has sent us a file named |interest_2013.txt|\r\n% that contains interest amounts for each month of the year. \r\n%%\r\n% For English-language dates and times, you can use the\r\n% <\r\n% Import Tool> to import your data graphically. However, the dates in our\r\n% file are written in German:\r\n%\r\n%  Date,Interest\r\n%  31. Januar 2013 12:00,1.93\r\n%  28. Februar 2013 12:00,4.28\r\n%  31. M\u00c3\u00a4rz 2013 12:00,4.82\r\n%  30. April 2013 12:00,1.23\r\n%  31. Mai 2013 12:00,5.89\r\n%  30. Juni 2013 12:00,2.26\r\n%  31. Juli 2013 12:00,3.84\r\n%  31. August 2013 12:00,5.82\r\n%  30. September 2013 12:00,2.51\r\n%  31. Oktober 2013 12:00,2.99\r\n%  30. November 2013 12:00,6.17\r\n%  31. Dezember 2013 12:00,2.65\r\n%\r\n%\r\n%% \r\n% For non-English language dates, we must import the data using functions.\r\n% We will use <https:\/\/www.mathworks.com\/help\/matlab\/ref\/readtable.html\r\n% |readtable|> to read the file data into a table.\r\n% Use the |%D| specifier to read the first column of data as |datetime| values and specify the\r\n% format of the date strings within curly braces. The |'DateLocale'| name-value pair\r\n% argument tells MATLAB how to interpret the date strings in the file. The\r\n% value of |DateLocale| is a combination of a lowercase\r\n% <http:\/\/en.wikipedia.org\/wiki\/List_of_ISO_639-1_codes language code> and an\r\n% uppercase <http:\/\/en.wikipedia.org\/wiki\/ISO_3166-1_alpha-2 country code>.\r\n% For example, |'de_CH'| indicates German-language dates in Switzerland.\r\nT = readtable('interest_2013.txt',...\r\n    'Format','%{dd.MMMM yyyy HH:mm}D %f','DateLocale','de_CH')\r\n%%\r\n% It appears that the bank's payments were made at noon each month, while\r\n% our own records indicate otherwise. What happened? Our original times are\r\n% based in Phoenix, whereas the imported times from the bank are\r\n% based in Zurich.\r\n%%\r\n% By default, |datetime| values are not associated with any time zone. That\r\n% is, they are \"unzoned\". Because we want to compare dates and times across\r\n% geographic locations and therefore\r\n% time zones, we should associate each |datetime| array with a time zone.\r\n% You can learn more about time zones\r\n% <https:\/\/www.mathworks.com\/help\/matlab\/matlab_prog\/specify-time-zones.html\r\n% here>.\r\n%\r\n%%\r\n% Let's set the time zone for our Phoenix-based |datetime| vector, |p|. Valid values for the |TimeZone| property include names of time zone regions from the\r\n% <http:\/\/www.iana.org\/time-zones IANA Time Zone Database>.  Then, adjust\r\n% the display format to show the UTC offset for each value.\r\np.TimeZone = 'America\/Phoenix';\r\np.Format = 'dd-MMM-yyyy HH:mm Z'\r\n%%\r\n% Unlike most of the United States, Phoenix does not observe daylight\r\n% saving time and is always 7 hours behind UTC.\r\n%%\r\n% Now, specify that the bank's payment times are in Zurich's time zone.\r\nz = T.Date;\r\nz.TimeZone = 'Europe\/Zurich';\r\nz.Format = 'dd-MMM-yyyy HH:mm Z'\r\n%%\r\n% In Zurich, the time zone offset changes during the year because Zurich\r\n% observes daylight saving time.\r\n%%\r\n% Now if we compare our payment times with the bank's data, we'll see that\r\n% they are the same.\r\nisequal(p,z)\r\n%% Not Every Day Has 24 Hours\r\n%%\r\n% On what day of the week were interest payments made? We can use the\r\n% <https:\/\/www.mathworks.com\/help\/matlab\/ref\/day.html |day|> function to\r\n% extract the day name from each value in |z|.\r\nd = day(z,'name')\r\n%%\r\n% The third payment date (March 31) falls on a Sunday. Suppose the \r\n% bank shifted this payment\r\n% date earlier by two days so that it would not fall on a weekend.\r\n%\r\n% What happens if we subtract a\r\n% |duration| of 2 standard, 24-hour long days to the corresponding payment\r\n% date?\r\nnew_date = z(3) - days(2)\r\n%%\r\n% Notice that the new payment time is now 11 AM instead of noon\r\n% because a daylight saving time shift occurred in Zurich on March\r\n% 30, 2014.\r\n%%\r\n% To account for a daylight saving time shift in a calendar calculation, we should subtract 2 _calendar\r\n% days_ from the original payment date.\r\n%%\r\nnew_date = z(3) - caldays(2)\r\n%%\r\n% Now the payment time is at noon, and is consistent with the payment\r\n% times during the rest of the year. If we calculate the exact _duration_ between the\r\n% original payment date and the new payment date, we will see that the\r\n% difference is not 48 hours (two 24-hour long days). Rather, the\r\n% difference is 47 hours due to the daylight saving time change.\r\nnew_date - z(3)\r\n%%\r\n% Here's the big takeaway: When a |datetime| value is associated with a time zone that observes\r\n% daylight saving time, it is affected by daylight saving time changes. To\r\n% correctly account for such time changes, make sure you use _calendar\r\n% durations_ instead of durations in calendar calculations involving days, months, or years.\r\n% |calendarDuration| values account for non-constant lengths of time such\r\n% as the length of a day, which is not always equal to 24 hours in some\r\n% time zones.\r\n%% Quarterly Statistics \r\n% Now we will calculate the mean of the interest payments for each quarter.\r\n% Just like how the |day| function can extract day names for each |datetime|\r\n% value in an array, the\r\n% <https:\/\/www.mathworks.com\/help\/matlab\/ref\/quarter.html |quarter|>\r\n% function lets us extract the quarter number.\r\nq = quarter(z)\r\n%%\r\n% Now we can calculate statistics for the interest payments associated\r\n% with each unique value of of |q|.\r\nfor ii = 1:4\r\n    X = sprintf('Quarter %d',ii);\r\n    disp(X)\r\n    tf = q==ii;\r\n    m_quarter = mean(T.Interest(tf)) \r\n    % T.Interest is a column containing interest values from \r\n    % the text file we imported earlier\r\nend\r\n%% Convert Date Numbers to Datetime\r\n% Now we've seen how to create |datetime| values and how to import date and time\r\n% data as |datetime| values that can account for time zones and daylight\r\n% saving time. But what if you currently have data in the form of serial\r\n% date numbers? Fear not, there's an easy way to convert your existing data\r\n% to more convenient datetime values. Let's start with an array of serial\r\n% date numbers:\r\ndn = (735600:31:735755)'\r\n%%\r\n% Use the |datetime| function to easily convert the date numbers to datetime\r\n% values.\r\np = datetime(dn,'ConvertFrom','datenum')\r\n%%\r\n% An array of serial date numbers cannot account for a time zone, but you\r\n% can add time zone information to the |datetime| array.\r\np.TimeZone = 'America\/New_York';\r\n%%\r\n% You can even export the |datetime| array in a different language. Let's\r\n% translate the dates into German and then export them to a text file.\r\nC = cellstr(p,'dd. MMMM yyyy','de_DE')\r\n%%\r\nT  = table(C,rand(6,1),'VariableNames',{'Date','InterestRate'})\r\n%%\r\nwritetable(T,'myfile.txt')\r\n%% Your Thoughts?\r\n% Have you tried using the |datetime|, |duration|, and |calendarDuration|\r\n% data types? Let us know what you think by leaving a comment <https:\/\/blogs.mathworks.com\/loren\/?p=1109#respond here>.\r\n\r\n##### SOURCE END ##### 1b37a49dfdb84f569bbd8cb54aa6fb0b\r\n-->","protected":false},"excerpt":{"rendered":"<!--introduction--><p>Once again we're going to hear from guest blogger Andrea Ho, who works for the MATLAB Documentation team here at MathWorks.... <a class=\"read-more\" href=\"https:\/\/blogs.mathworks.com\/loren\/2015\/03\/11\/matlab-data-types-for-dates-and-time-part-ii\/\">read more >><\/a><\/p>","protected":false},"author":39,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":[],"categories":[39,6],"tags":[],"_links":{"self":[{"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/posts\/1109"}],"collection":[{"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/users\/39"}],"replies":[{"embeddable":true,"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/comments?post=1109"}],"version-history":[{"count":3,"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/posts\/1109\/revisions"}],"predecessor-version":[{"id":1113,"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/posts\/1109\/revisions\/1113"}],"wp:attachment":[{"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/media?parent=1109"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/categories?post=1109"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/tags?post=1109"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}