Inconsistency when assigning to the 'Month' property of a datetime array in a timetable

3 次查看(过去 30 天)
I imported a timetable from an excel file and had to adjust some parts of the datetime array afterwards, since the original excel file had no information on the day, month, or year of the time column.
Since that info was missing from the input file, Matlab auto-filled the date so that I get a time column with entries like "1899-12-31 10:15:10". This matches the datetime format I set up in the import options - "yyyy-MM-dd HH:mm:ss".
Since I wanted to adjust the date to "2024-02-15", I used dot notation first for the year:
Table.TimeColumn.Year = 2024
This gave me the expected result of "2024-12-31 10:15:10". Where it gets weird is trying to change the month to February; if I enter something like this:
Table.TimeColumn.Month = 2
The days of the datetime values get changed to "2" instead, and the month is set to March, like this: "2024-03-02 10:15:10".
What's even stranger is that assigning the month value to "1" or "3" does not replicate this behavior. Using those values changes the month as expected.
But when assigning the datetime's month to "2", I can only change the month to my desired value if I make another dot notation assignment for it after the first one, or assign it after adjusting the day value, such that this
Table.TimeColumn.Year = 2024
Table.TimeColumn.Month = 2
Table.TimeColumn.Day = 15
puts out "2024-03-15", while this
Table.TimeColumn.Year = 2024
Table.TimeColumn.Day = 15
Table.TimeColumn.Month = 2
puts out "2024-02-15" in my timetable column.
Is this possibly a bug, or am I not understanding the format correctly?

采纳的回答

Steven Lord
Steven Lord 2024-2-26
From the old rhyme, "Save February at twenty-eight, // But leap year, coming once in four, // February then has one day more."
What is February 31st? It's a non-standard date.
dt = datetime(2024, 2, 31)
dt = datetime
02-Mar-2024
It ought to be February 29th plus two calendar days, right? Since 29 + 2 = 31.
dt = datetime(2024, 2, 29) + caldays(2)
dt = datetime
02-Mar-2024
You'd run into this same scenario with changing the month of a datetime from a 31-day month to a 30-day month. For example, March has 31 days while April has 30 but not 31.
dt1 = datetime(2024, 3, 31)
dt1 = datetime
31-Mar-2024
dt2 = datetime(2024, 4, 30)
dt2 = datetime
30-Apr-2024
If I change dt1's Month to be April, it becomes May 1st aka "April 31st".
dt1.Month = 4
dt1 = datetime
01-May-2024
dt3 = datetime(2024, 4, 31)
dt3 = datetime
01-May-2024

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Calendar 的更多信息

标签

产品


版本

R2023b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by