1.说明
时间点和(日历)持续时间是可加的,结果是时间点;两个时间点是可减的,结果是持续时间,用时分秒表示;时间型和浮点数运算,结果是时间型,浮点数默认单位是天;由于日历时间的不确定,加减日历时间所得结果与加减顺序有关。
2. datetime和duration的算术运算
程序示例如下:
t1=datetime
t2=t1+hours(1) %时间点+持续时间=时间点
t2=t1+hours(0:2) %%0表示当前,1表示下一个
t21=t1+days(0:2)
运行结果:
t1 =
datetime
2025-02-15 21:15:07
t2 =
datetime
2025-02-15 22:15:07
t2 =
1×3 datetime 数组
2025-02-15 21:15:07 2025-02-15 22:15:07 2025-02-15 23:15:07
t21 =
1×3 datetime 数组
2025-02-15 21:15:07 2025-02-16 21:15:07 2025-02-17 21:15:07
t21=t1+[0 1 2] %单个数字默认使用 天 为单位
dt=t2-t1 %时间点相减变成持续时间
dt21=t21-t1 %持续时间默认使用 时分秒 的形式表示
运行结果:
t21 =
1×3 datetime 数组
2025-02-15 21:15:07 2025-02-16 21:15:07 2025-02-17 21:15:07
dt =
1×3 duration 数组
00:00:00 01:00:00 02:00:00
dt21 =
1×3 duration 数组
00:00:00 24:00:00 48:00:00
3. duration的算术运算
程序示例如下:
hours(1)+minutes(30) %持续时间自身累加,默认使用 小时 表示
hours(1)+1
运行结果:
ans =
duration
1.5小时
ans =
duration
25小时

4. calendarduration的运算
程序示例如下:
t3=datetime('today')
t31=t3+calmonths(0:2)
t31-t3 %两个时间点相减产生持续时间类型duration,默认使用 时分秒 的形式表示
t6=t3+calmonths(0:2)+caldays(0:2)
t6-t3 %获取持续时间
运行结果:
t3 =
datetime
2025-02-15
t31 =
1×3 datetime 数组
2025-02-15 2025-03-15 2025-04-15
ans =
1×3 duration 数组
00:00:00 672:00:00 1416:00:00
t6 =
1×3 datetime 数组
2025-02-15 2025-03-16 2025-04-17
ans =
1×3 duration 数组
00:00:00 696:00:00 1464:00:00
5.时间序列差分运算
时间序列差分运算使用函数diff、caldiff,程序示例如下:
diff(t2)
diff(t21)
cdf31=caldiff(t31) %一个时间序列内部之间的持续时间,产生日历持续时间calendarduration
cdf31=caldiff(t31,'days') %按 天 计算
运行结果:
ans =
1×2 duration 数组
01:00:00 01:00:00
ans =
1×2 duration 数组
24:00:00 24:00:00
cdf31 =
1×2 calendarDuration 数组
1mo 1mo
cdf31 =
1×2 calendarDuration 数组
28d 31d
6.日历时间差分between
程序示例如下:
between(t3,t6) %用between函数,产生日历持续时间类型,按照日历时间计算两个运算数之间的时间间隔
运行结果:
ans =
1×3 calendarDuration 数组
0d 1mo 1d 2mo 2d
7.日历时间综合运算实例
由于日历持续时间随着具体的日历变化,加减日历持续时间所得结果与加减顺序有关,程序示例如下:
t33=datetime(2014,1,31) + calmonths(1) + caldays(30)
t34=datetime(2014,1,31) + caldays(30) + calmonths(1)
t33=datetime(2014,1,31) + calmonths(1) %2月28天,加一个日历月只能到达2.28
t34=datetime(2014,1,31) + caldays(30) %加30天要数到3.2
运行结果:
t33 =
datetime
2014-03-30
t34 =
datetime
2014-04-02
t33 =
datetime
2014-02-28
t34 =
datetime
2014-03-02
8.日历持续时间的特殊性
t5=calyears(2) + calmonths(2) + caldays(2) %日历持续时间自身累加,仍然用字面的年月日表示,无法整合,因为日历时间的长度未知
%%可以使用calquarters,calweeks和caldays函数添加或减去日历季度,日历周,或日历日
运行结果:
t5 =
calendarDuration
2y 2mo 2d
免责声明:本文系网络转载或改编,未找到原创作者,版权归原作者所有。如涉及版权,请联系删