从文本文件中导入日期时间
要从列向表格数据中导入格式化的日期时间(例如 '01/01/01'
或 '12:30:45'
),有如下三种方法可以选择。
导入工具 - 以交互方式选择并导入日期时间。
readtable
函数 - 自动检测包含日期时间的变量,并将其导入到表中。导入选项 - 将
readtable
函数与detectImportOptions
配合使用,以便对日期时间变量的导入实行更多控制。例如,可以指定FillValue
和DatetimeFormat
等属性。
此示例说明如何使用以上各种方法从文本文件中导入日期时间。
导入工具
使用导入工具打开文件 outages.csv
。使用每列的下拉菜单指定日期时间的格式。您可以从预定义的日期格式中选择,或者输入自定义格式。要导入 OutageTime
列,请指定自定义格式 yyyy-MM-dd HH:mm
。然后,点击导入所选内容按钮,将数据导入到工作区中。
readtable
函数
使用 readtable
函数并显示 OutageTime
变量的前 10
行。readtable
会自动检测日期时间变量和格式。
filename = 'outages.csv';
T = readtable(filename);
T.OutageTime(1:10)
ans = 10x1 datetime
01-Feb-2002 12:18:00
23-Jan-2003 00:49:00
07-Feb-2003 21:15:00
06-Apr-2004 05:44:00
16-Mar-2002 06:18:00
18-Jun-2003 02:49:00
20-Jun-2004 14:39:00
06-Jun-2002 19:28:00
16-Jul-2003 16:23:00
27-Sep-2004 11:09:00
导入选项
使用导入选项对象,对日期时间变量的导入实行更多控制。例如,更改日期时间显示格式,或指定缺失日期的填充值。
为 outages.csv
文件创建导入选项对象,并显示变量 RestorationTime
的变量导入选项。detectImportOptions
函数会自动检测变量的数据类型。
opts = detectImportOptions(filename);
getvaropts(opts,'RestorationTime')
ans = DatetimeVariableImportOptions with properties: Variable Properties: Name: 'RestorationTime' Type: 'datetime' FillValue: NaT TreatAsMissing: {} QuoteRule: 'remove' Prefixes: {} Suffixes: {} EmptyFieldRule: 'missing' Datetime Options: DatetimeFormat: 'default' DatetimeLocale: 'en_US' InputFormat: '' TimeZone: ''
导入数据并显示变量 RestorationTime
的前 10
行。第二行包含一个 NaT
,指示缺失的日期时间值。
T = readtable(filename,opts); T.RestorationTime(1:10)
ans = 10x1 datetime
07-Feb-2002 16:50:00
NaT
17-Feb-2003 08:14:00
06-Apr-2004 06:10:00
18-Mar-2002 23:23:00
18-Jun-2003 10:54:00
20-Jun-2004 19:16:00
07-Jun-2002 00:51:00
17-Jul-2003 01:12:00
27-Sep-2004 16:37:00
要使用其他日期时间显示格式,请更新 DatetimeFormat
属性,然后通过使用 FillValue
属性,将缺失的值替换为当前的日期时间。显示更新的变量选项。
opts = setvaropts(opts,'RestorationTime', ... 'DatetimeFormat','MMMM d, yyyy HH:mm:ss Z',... 'FillValue','now'); getvaropts(opts,'RestorationTime')
ans = DatetimeVariableImportOptions with properties: Variable Properties: Name: 'RestorationTime' Type: 'datetime' FillValue: January 25, 2024 22:25:19 * TreatAsMissing: {} QuoteRule: 'remove' Prefixes: {} Suffixes: {} EmptyFieldRule: 'missing' Datetime Options: DatetimeFormat: 'MMMM d, yyyy HH:mm:ss Z' DatetimeLocale: 'en_US' InputFormat: '' TimeZone: ''
使用更新的导入选项读取数据,并显示变量的前 10
行。
T = readtable(filename,opts); T.RestorationTime(1:10)
ans = 10x1 datetime
February 7, 2002 16:50:00 *
January 25, 2024 22:25:19 *
February 17, 2003 08:14:00 *
April 6, 2004 06:10:00 *
March 18, 2002 23:23:00 *
June 18, 2003 10:54:00 *
June 20, 2004 19:16:00 *
June 7, 2002 00:51:00 *
July 17, 2003 01:12:00 *
September 27, 2004 16:37:00 *
有关 datetime
变量选项的详细信息,请参阅 setvaropts
参考页。
另请参阅
导入工具 | readtable
| detectImportOptions
| setvaropts
| readmatrix
| readcell
| readvars
| readtimetable