datetime.datetime
datetime: T = datetime ('now')
datetime: T = datetime ('today')
datetime: T = datetime ('tomorrow')
datetime: T = datetime ('yesterday')
datetime: T = datetime (DateStrings)
datetime: T = datetime (DateStrings, 'MixedFormats', TF)
datetime: T = datetime (DateStrings, 'InputFormat', INFMT)
datetime: T = datetime (DateStrings,'InputFormat', INFMT, 'PivotYear', PIVOT)
datetime: T = datetime (DateStrings,'InputFormat', INFMT, 'Locale', LOCALE)
datetime: T = datetime (DateVectors)
datetime: T = datetime (Y, MO, D)
datetime: T = datetime (Y, MO, D, H, MI, S)
datetime: T = datetime (Y, MO, D, H, MI, S, MS)
datetime: T = datetime (X, 'ConvertFrom', TYPE)
datetime: T = datetime (D)
datetime: T = datetime (…, 'Format', FMT)
datetime: T = datetime (…, 'TimeZone', TZ)
Create a new array of datetime values.
T = datetime ( returns a scalar datetime array
corresponding to the current date and time. 'now')T = datetime
( is the same as 'now')T = datetime (). Except for
'now', the same syntax can be used with 'today',
'tomorrow' and 'yesterday'. These options return the
respective date but with time set at midnight.
T = datetime (DateStrings) creates a datetime array
from the text in DateStrings representing points in time. Without
an 'InputFormat', one format is detected from the first piece of
text that is not blank, and every other piece is then read with that same
format: text written in a different one is not given a format of its own
but becomes NaT, so that a column of dates is read as the single
thing it is meant to be. Text no format can be detected from at all is
refused outright. A date that the detected format cannot make sense of,
such as '2024-04-31', is refused in the same way an explicit
'InputFormat' refuses it.
The formats detected are:
'uuuu-MM-dd' | optionally followed by 'HH:mm',
'HH:mm:ss', or either with fractional seconds, the date and the
time separated by a space or by 'T'. |
'dd-MMM-uuuu' | month named in full or abbreviated, optionally followed by a time as above. |
'MMMM d, uuuu' | as in 'March 15, 2024'. |
'MM/dd/uuuu' | or 'dd/MM/uuuu'; see below. |
'HH:mm:ss' | a time alone, taking today’s date. |
Source Code: datetime
Three further shapes are read that MATLAB does not detect, and are
Octave extensions: 'uuuu/MM/dd' with an optional time,
'dd MMMM uuuu' as in '15 March 2024', and a year alone.
Numeric fields need not be padded, so '2024-2-9' reads as
'2024-02-09' does.
A date written with slashes is ambiguous: '03/09/2024' is the 3rd
of September to some readers and the 9th of March to others. The whole
array decides, since one entry naming a day past the twelfth settles the
order for all of them; where nothing settles it the American reading is
taken and a warning
('Octave:datetime:ambiguous-format') is raised.
T = datetime (DateStrings, detects a format for each piece of text separately instead,
so text gathered from several sources into one column is read whatever
each entry happens to be written in. This is an Octave extension, off by
default; MATLAB has no equivalent. It reads the wider set of formats
Octave’s core 'MixedFormats',
true)datevec accepts, and rolls an impossible date over
rather than refusing it, so '2024-04-31' is read as the 1st of
May. It cannot tell a mistake from a format it has not seen before,
which is why it is not the default.
T = datetime (DateStrings, also allows to specify a particular input text format to
parse DateStrings. It is always preferable to specify the format
INFMT if it is known. INFMT uses the Unicode LDML date field
symbols ('InputFormat',
INFMT)'y', 'M', 'd', 'H', 'h',
'm', 's', 'S', 'a', …), the same
set used for display formats; text between single quotes is treated as a
literal. Formats which do not specify a particular time component will
have the value set to zero. Formats which do not specify any date
component default to the current date, whereas a partially specified date
defaults its missing month and day to 1.
A string that does not match INFMT, or that names a date which does
not exist, such as '2024-04-31' or a 29th of February outside a
leap year, cannot be converted. A lone such string is an error; within
an array only that element is lost and becomes NaT, so that one
unreadable entry does not cost the rest of the array.
T = datetime (DateStrings, also allows to specify a
pivot year, which refers to the year at the start of the century to which
two-digit years will be referenced. When not specified, it defaults to
the current year minus 50.
'InputFormat',
INFMT, 'PivotYear', PIVOT)
T = datetime (DateStrings, interprets the month names,
weekday names, and day-period markers in DateStrings according to
LOCALE, given as an 'InputFormat',
INFMT, 'Locale', LOCALE)'xx_YY' identifier whose language part
selects the names. The supported languages are 'en' (the
default), 'fr', 'de', 'es', 'it',
'pt', and 'el'; 'system' is treated as
'en'. Both full ('MMMM'/'eeee') and abbreviated
('MMM'/'eee') month and weekday names are recognized
case-insensitively; for Greek, matching is also accent-insensitive, so
the accentless all-caps spelling is accepted, and the genitive month
forms ('Μαρτίου') are used. A weekday name is validated but does
not otherwise affect the result.
T = datetime (DateVectors) creates a column vector of
datetime values from the date vectors in DateVectors.
T = datetime (Y, MO, D creates an array of
datetime values for corresponding elements of the Y, MO, and
D arrays, which must be of the same size or scalars, must contain
integer values, and they correspond to years, months, and days,
respectively.
T = datetime (Y, MO, D, H, MI,
S) also adds time components to the constructed datetime arrays.
H, MI, and S must be of the same size or scalars.
H and MI must contain integer values, whereas S may
also contain a fractional part.
T = datetime (Y, MO, D, H, MI,
S, MS) also adds a milliseconds component, MS, which
may also have a fractional part.
T = datetime (X,
converts the numeric values in X to a datetime array according to
the data type specified by TYPE. The following types are
supported:
'ConvertFrom', TYPE)
'datenum'
'excel'
'excel1904'
'posixtime'
'epochtime'
'juliandate'
'modifiedjuliandate'
'yyyymmdd'
'ntp' – requires uint64 input.
'ntfs' – requires uint64 input.
'.net' – requires uint64 input.
'tt2000' – requires int64 input and the
'UTCLeapSeconds' time zone (see convertTo).
'Epoch' (a scalar datetime marking tick zero, default
1970-01-01) and 'TicksPerSecond' (a positive scalar,
default 1) bear on 'epochtime' alone; they are accepted
alongside any other conversion and ignored, each of the others counting
from an epoch of its own.
Whether the count measures elapsed or wall-clock time
follows from the epoch. When the epoch and 'TimeZone' are
both zoned the count is elapsed time from a known instant, so
datetime (X, 'ConvertFrom', 'epochtime', 'Epoch',
datetime (1970, 1, 1, 'TimeZone', 'UTC'), 'TimeZone', Z) agrees
with 'posixtime'. Otherwise the epoch is a wall clock, its zone
dropped if it had one, and so is the count – which is why the
default does not agree with 'posixtime': its epoch is
unzoned, so 1730611800 names 05:30 on the local clock of whatever
zone is asked for rather than the instant 05:30 UTC. That is not an
inconsistency but the meaning of an epoch-relative count, and MATLAB
reads it the same way.
Each is the inverse of the convertTo conversion of the same name
and treats an inserted leap second the way that conversion does, so the
two round-trip. Where the conversion folded the inserted second away –
'datenum', 'excel', 'excel1904',
'epochtime', 'ntp', 'ntfs' and '.net'
all do – it cannot be recovered and the preceding second is returned,
just as those conversions give the two instants of a repeated wall clock
the same value. The Julian scales measure the fraction of a day against
that day’s own length and so keep an inserted second, returning
23:59:60 where one was given. A Julian day number is a large one
and a double holds it to about 40 microseconds at present-day dates,
which bounds the accuracy of 'juliandate' in both directions;
'modifiedjuliandate' counts from a nearer epoch and is some
forty times finer.
Deviation from MATLAB. For a 'UTCLeapSeconds' array,
'epochtime' given an 'Epoch' counts both operands on the
same timeline here, while MATLAB folds the array onto the POSIX one and
measures the epoch on the leap-second one, so its answer runs long by the
seconds inserted before that epoch: counting 86399 from
2016-12-31 it returns 2017-01-01T00:00:25, 26 seconds past
the 23:59:59 that both consistent readings give. This is the same
inconsistency already documented for convertTo in the other
direction, and inverting it the same way is what makes the pair
round-trip.
Deviation from MATLAB. For a 'UTCLeapSeconds' array,
MATLAB’s 'juliandate' does not invert its own
convertTo (T, 'juliandate'): it returns an instant half a
second later than the one it was given, on the day of an inserted second
and for every element of it. Its 'modifiedjuliandate' inverts
correctly over the same day, so the two disagree with each other as well.
The conversion here inverts exactly, in both scales. This is the same
half-day slip already documented for 'tt2000' between 1960 and
1972 in convertTo.
T = datetime (D), where D is already a datetime
array, copies it: the components, the TimeZone and the
Format all carry over. A 'Format' or 'TimeZone'
may still be given to change either, and take effect exactly as assigning
those properties does, so attaching a zone to an unzoned array keeps its
wall-clock values whereas changing between two zones keeps the instant.
The options describing how text is read, 'InputFormat',
'Locale' and 'PivotYear', have nothing to act on and are
ignored, while 'ConvertFrom' is an error.
T = datetime (…,
specifies the display format of the values in the output datetime array.
FMT uses the same Unicode LDML date field symbols as
'Format', FMT)'InputFormat', with 'z', 'Z', 'X', and
'x' additionally naming the time zone, and text between single
quotes taken literally. The default format renders a date alone when
every element sits at midnight and a date with a time otherwise; a
NaT carries no time of day and does not affect that choice.
T = datetime (…, sets
the time zone of the values in the output datetime array. If not
specified, the array is unzoned: its values are wall-clock readings that
name no absolute instant, and no daylight saving rule applies to them.
Supported time zones are those of the IANA Time Zone Database. A zone
may also be attached, changed, or dropped afterwards through the
'TimeZone', TZ)'TimeZone' property; attaching one reinterprets the wall-clock
values in that zone, whereas changing between two zones preserves the
absolute instant and shifts the wall-clock values by the difference in
offset.
Twice a year a zone that observes Daylight Saving Time (DST) has
wall-clock readings that name no unique instant. Where the clock goes
back an hour repeats, and such a reading is taken at the later of the two
offsets, that is, standard time. Where the clock goes forward an
interval is skipped, and a reading inside it is one no clock in that zone
ever shows. Given as numeric components, such a reading is moved ahead
by the length of the skipped interval, so that with the usual one-hour
skip '02:30' becomes '03:30'; given as text it is instead
rejected, since text is a claim about a reading that never occurred. A
lone such string is an error, whereas within an array only that element
is lost and becomes NaT; without an 'InputFormat' the
whole input is rejected, as when no format can be detected at all.
In the 'UTCLeapSeconds' zone the seconds component may reach 60,
naming an inserted leap second, but only on one of the 27 dates that has
one and only in the last minute of the day; anywhere else it rolls over
as usual. The seconds component is counted along the leap-second
timeline, so '23:59:61' on such a date is the next midnight
rather than one second past it, whereas an hour or minute that overflows
over the inserted second entirely. Text naming a leap second that was
never inserted is rejected, exactly as text naming a wall clock a zone
skips is. Without an 'InputFormat' such an array reads only the
ISO 8601 UTC shape it also writes.
Deviations from MATLAB when copying a datetime array and giving
a 'TimeZone'. MATLAB’s constructor keeps the display format of
the array it copies, while its TimeZone property assignment
replaces it for the same change of zone; the two disagree, so here both
follow the one rule, that of the property. Leaving
'UTCLeapSeconds' therefore restores the ordinary default format
rather than keeping the ISO 8601 pattern, whose 'Z' would
misdescribe any zone but UTC. For the same reason, entering
'UTCLeapSeconds' works here, the locked format being applied,
where MATLAB carries the copied format across and then rejects it as one
that zone does not allow.
See also: NaT, datetime, isdatetime, calendarDuration, duration
Source Code: datetime
A datetime is a specific point in time. The simplest form gives the year, month and day; add hour, minute and second for a time of day.
datetime (2024, 3, 9)
ans = datetime 09-Mar-2024
datetime (2024, 3, 9, 14, 30, 15)
ans = datetime 09-Mar-2024 14:30:15
Text is parsed automatically for the common ISO and dd-MMM-yyyy layouts.
datetime ('2024-03-09')
ans = datetime 09-Mar-2024
datetime ('09-Mar-2024 14:30:15')
ans = datetime 09-Mar-2024 14:30:15
A single numeric row is read as a date vector [Y M D h m s], and a range of datetimes is built with the colon operator and a step — here one calendar day with caldays.
datetime ([2024, 3, 9, 14, 30, 15])
ans = datetime 09-Mar-2024 14:30:15
datetime (2024, 1, 1) : caldays (1) : datetime (2024, 1, 4)
ans =
1x4 datetime array
01-Jan-2024 02-Jan-2024 03-Jan-2024 04-Jan-2024
The defining feature of datetime is time-zone awareness. Attach a zone with 'TimeZone' and the value becomes a true instant: tzoffset reports its offset from UTC, and arithmetic across a daylight-saving change is handled for you.
t = datetime (2024, 3, 9, 14, 30, 0, 'TimeZone', 'America/New_York')
t = datetime 09-Mar-2024 14:30:00
tzoffset (t)
ans = duration -05:00
The 'Format' property controls display only, never the stored value. Here the SAME instant is shown several ways by setting different Unicode (LDML) field patterns — y year, M month, d day, H hour, e weekday.
datetime (2024, 3, 9, 14, 30, 15, 'Format', 'yyyy-MM-dd HH:mm:ss')
ans = datetime 2024-03-09 14:30:15
datetime (2024, 3, 9, 14, 30, 15, 'Format', 'MMMM d, yyyy')
ans = datetime March 9, 2024
datetime (2024, 3, 9, 14, 30, 15, 'Format', 'eeee')
ans = datetime Saturday
By default the display omits sub-seconds even though they are stored — ask for them explicitly with fractional-second (S) codes.
datetime (2024, 3, 9, 14, 30, 15.5)
ans = datetime 09-Mar-2024 14:30:15
datetime (2024, 3, 9, 14, 30, 15.5, 'Format', 'HH:mm:ss.SSS')
ans = datetime 14:30:15.500
A missing datetime is NaT (Not-a-Time), the datetime analogue of NaN; a NaN component produces one.
NaT
ans = datetime NaT
datetime (2024, 1, [1, NaN, 3])
ans =
1x3 datetime array
01-Jan-2024 NaT 03-Jan-2024