Inconsistency when assigning to the 'Month' property of a datetime array in a timetable
4 views (last 30 days)
Show older comments
Michael Butler
on 26 Feb 2024
Answered: Steven Lord
on 26 Feb 2024
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?
0 Comments
Accepted Answer
Steven Lord
on 26 Feb 2024
From the old rhyme, "Save February at twenty-eight, // But leap year, coming once in four, // February then has one day more."
dt = datetime(2024, 2, 31)
It ought to be February 29th plus two calendar days, right? Since 29 + 2 = 31.
dt = datetime(2024, 2, 29) + caldays(2)
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)
dt2 = datetime(2024, 4, 30)
If I change dt1's Month to be April, it becomes May 1st aka "April 31st".
dt1.Month = 4
dt3 = datetime(2024, 4, 31)
0 Comments
More Answers (0)
See Also
Categories
Find more on Calendar in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!