Dates and Time¶
Dates and Time Types¶
Period¶Year¶Month¶Week¶Day¶Hour¶Minute¶Second¶Millisecond¶Periodtypes represent discrete, human representations of time.
CompoundPeriod¶A
CompoundPeriodis useful for expressing time periods that are not a fixed multiple of smaller periods. For example, “a year and a day” is not a fixed number of days, but can be expressed using aCompoundPeriod. In fact, aCompoundPeriodis automatically generated by addition of different period types, e.g.Year(1)+Day(1)produces aCompoundPeriodresult.
Instant¶Instanttypes represent integer-based, machine representations of time as continuous timelines starting from an epoch.
UTInstant{T}¶The
UTInstantrepresents a machine timeline based on UT time (1 day = one revolution of the earth). TheTis aPeriodparameter that indicates the resolution or precision of the instant.
TimeType¶TimeTypetypes wrapInstantmachine instances to provide human representations of the machine instant. BothDateTimeandDateare subtypes ofTimeType.
DateTime¶DateTimewraps aUTInstant{Millisecond}and interprets it according to the proleptic Gregorian calendar.
Date¶Datewraps aUTInstant{Day}and interprets it according to the proleptic Gregorian calendar.
Dates Functions¶
All Dates functions are defined in the Dates module; note that only the Date, DateTime, and now functions are exported;
to use all other Dates functions, you’ll need to prefix each function call with an explicit Dates., e.g. Dates.dayofweek(dt).
Alternatively, you can write usingBase.Dates to bring all exported functions into Main to be used without the Dates. prefix.
DateTime(y[, m, d, h, mi, s, ms]) → DateTimeConstruct a
DateTimetype by parts. Arguments must be convertible toInt64.
DateTime(periods::Period...) → DateTimeConstruct a
DateTimetype byPeriodtype parts. Arguments may be in any order. DateTime parts not provided will default to the value ofDates.default(period).
DateTime(f::Function, y[, m, d, h, mi, s]; step=Day(1), negate=false, limit=10000) → DateTimeCreate a
DateTimethrough the adjuster API. The starting point will be constructed from the providedy,m,d...arguments, and will be adjusted untilf::Functionreturnstrue. The step size in adjusting can be provided manually through thestepkeyword. Ifnegate=true, then the adjusting will stop whenf::Functionreturnsfalseinstead oftrue.limitprovides a limit to the max number of iterations the adjustment API will pursue before throwing an error (in the case thatf::Functionis never satisfied).
DateTime(dt::Date) → DateTimeConverts a
Dateto aDateTime. The hour, minute, second, and millisecond parts of the newDateTimeare assumed to be zero.
DateTime(dt::AbstractString, format::AbstractString; locale="english") → DateTimeConstruct a
DateTimeby parsing thedtdate string following the pattern given in theformatstring. The following character codes can be used to construct theformatstring:Code Matches Comment y1996, 96 Returns year of 1996, 0096 Y1996, 96 Returns year of 1996, 0096. Equivalent to ym1, 01 Matches 1 or 2-digit months uJan Matches abbreviated months according to the localekeywordUJanuary Matches full month names according to the localekeywordd1, 01 Matches 1 or 2-digit days H00 Matches hours M00 Matches minutes S00 Matches seconds s.500 Matches milliseconds eMon, Tues Matches abbreviated days of the week EMonday Matches full name days of the week yyyymmdd19960101 Matches fixed-width year, month, and day Characters not listed above are normally treated as delimiters between date and time slots. For example a
dtstring of “1996-01-15T00:00:00.0” would have aformatstring like “y-m-dTH:M:S.s”. If you need to use a code character as a delimiter you can escape it using backslash. The date “1995y01m” would have the format “y\ym\m”.
format(dt::TimeType, format::AbstractString; locale="english") → AbstractString¶Construct a string by using a
TimeTypeobject and applying the providedformat. The following character codes can be used to construct theformatstring:Code Examples Comment y6 Numeric year with a fixed width Y1996 Numeric year with a minimum width m1, 12 Numeric month with a minimum width uJan Month name shortened to 3-chars according to the localeUJanuary Full month name according to the localekeywordd1, 31 Day of the month with a minimum width H0, 23 Hour (24-hour clock) with a minimum width M0, 59 Minute with a minimum width S0, 59 Second with a minimum width s000, 500 Millisecond with a minimum width of 3 eMon, Tue Abbreviated days of the week EMonday Full day of week name The number of sequential code characters indicate the width of the code. A format of
yyyy-mmspecifies that the codeyshould have a width of four whilema width of two. Codes that yield numeric digits have an associated mode: fixed-width or minimum-width. The fixed-width mode left-pads the value with zeros when it is shorter than the specified width and truncates the value when longer. Minimum-width mode works the same as fixed-width except that it does not truncate values longer than the width.When creating a
formatyou can use any non-code characters as a separator. For example to generate the string “1996-01-15T00:00:00” you could useformat: “yyyy-mm-ddTHH:MM:SS”. Note that if you need to use a code character as a literal you can use the escape character backslash. The string “1996y01m” can be produced with the format “yyyy\ymm\m”.
DateFormat(format::AbstractString, locale::AbstractString="english") → DateFormat¶Construct a date formatting object that can be used for parsing date strings or formatting a date object as a string. For details on the syntax for
formatsee parsing and formatting.
DateTime(dt::AbstractString, df::DateFormat) → DateTimeConstruct a
DateTimeby parsing thedtdate string following the pattern given in theDates.DateFormat()object. Similar toDateTime(::AbstractString,::AbstractString)but more efficient when repeatedly parsing similarly formatted date strings with a pre-createdDateFormatobject.
Date(y[, m, d]) → DateConstruct a
Datetype by parts. Arguments must be convertible toInt64.
Date(period::Period...) → DateConstruct a
Datetype byPeriodtype parts. Arguments may be in any order.Dateparts not provided will default to the value ofDates.default(period).
Date(f::Function, y[, m, d]; step=Day(1), negate=false, limit=10000) → DateCreate a
Datethrough the adjuster API. The starting point will be constructed from the providedy,m,darguments, and will be adjusted untilf::Functionreturnstrue. The step size in adjusting can be provided manually through thestepkeyword. Ifnegate=true, then the adjusting will stop whenf::Functionreturnsfalseinstead oftrue.limitprovides a limit to the max number of iterations the adjustment API will pursue before throwing an error (given thatf::Functionis never satisfied).
Date(dt::DateTime) → DateConverts a
DateTimeto aDate. The hour, minute, second, and millisecond parts of theDateTimeare truncated, so only the year, month and day parts are used in construction.
Date(dt::AbstractString, format::AbstractString; locale="english") → DateConstruct a
Dateobject by parsing adtdate string following the pattern given in theformatstring. Follows the same conventions asDateTime(::AbstractString,::AbstractString).
Date(dt::AbstractString, df::DateFormat) → DateParse a date from a date string
dtusing aDateFormatobjectdf.
now() → DateTime¶Returns a
DateTimecorresponding to the user’s system time including the system timezone locale.
now(::Type{UTC}) → DateTimeReturns a
DateTimecorresponding to the user’s system time as UTC/GMT.
eps(::DateTime) → Millisecond¶eps(::Date) → DayReturns
Millisecond(1)forDateTimevalues andDay(1)forDatevalues.
Accessor Functions¶
year(dt::TimeType) → Int64¶The year of a
DateorDateTimeas anInt64.
month(dt::TimeType) → Int64¶The month of a
DateorDateTimeas anInt64.
week(dt::TimeType) → Int64¶Return the ISO week date of a
DateorDateTimeas anInt64. Note that the first week of a year is the week that contains the first Thursday of the year which can result in dates prior to January 4th being in the last week of the previous year. For exampleweek(Date(2005,1,1))is the 53rd week of 2004.
day(dt::TimeType) → Int64¶The day of month of a
DateorDateTimeas anInt64.
hour(dt::DateTime) → Int64¶The hour of day of a
DateTimeas anInt64.
minute(dt::DateTime) → Int64¶The minute of a
DateTimeas anInt64.
second(dt::DateTime) → Int64¶The second of a
DateTimeas anInt64.
millisecond(dt::DateTime) → Int64¶The millisecond of a
DateTimeas anInt64.
Year(dt::TimeType) → YearThe year part of a
DateorDateTimeas aYear.
Month(dt::TimeType) → MonthThe month part of a
DateorDateTimeas aMonth.
Week(dt::TimeType) → WeekThe week part of a
DateorDateTimeas aWeek. For details seeweek().
Day(dt::TimeType) → DayThe day part of a
DateorDateTimeas aDay.
Hour(dt::DateTime) → HourThe hour part of a
DateTimeas aHour.
Minute(dt::DateTime) → MinuteThe minute part of a
DateTimeas aMinute.
Second(dt::DateTime) → SecondThe second part of a
DateTimeas aSecond.
Millisecond(dt::DateTime) → MillisecondThe millisecond part of a
DateTimeas aMillisecond.
yearmonth(dt::TimeType) → (Int64, Int64)¶Simultaneously return the year and month parts of a
DateorDateTime.
monthday(dt::TimeType) → (Int64, Int64)¶Simultaneously return the month and day parts of a
DateorDateTime.
yearmonthday(dt::TimeType) → (Int64, Int64, Int64)¶Simultaneously return the year, month and day parts of a
DateorDateTime.
Query Functions¶
dayname(dt::TimeType; locale="english") → AbstractString¶Return the full day name corresponding to the day of the week of the
DateorDateTimein the givenlocale.
dayabbr(dt::TimeType; locale="english") → AbstractString¶Return the abbreviated name corresponding to the day of the week of the
DateorDateTimein the givenlocale.
dayofweek(dt::TimeType) → Int64¶Returns the day of the week as an
Int64with1=Monday,2=Tuesday,etc..
dayofmonth(dt::TimeType) → Int64¶The day of month of a
DateorDateTimeas anInt64.
dayofweekofmonth(dt::TimeType) → Int¶For the day of week of
dt, returns which number it is indt‘s month. So if the day of the week ofdtis Monday, then1=FirstMondayofthemonth,2=SecondMondayofthemonth,etc.In the range 1:5.
daysofweekinmonth(dt::TimeType) → Int¶For the day of week of
dt, returns the total number of that day of the week indt‘s month. Returns 4 or 5. Useful in temporal expressions for specifying the last day of a week in a month by includingdayofweekofmonth(dt)==daysofweekinmonth(dt)in the adjuster function.
monthname(dt::TimeType; locale="english") → AbstractString¶Return the full name of the month of the
DateorDateTimein the givenlocale.
monthabbr(dt::TimeType; locale="english") → AbstractString¶Return the abbreviated month name of the
DateorDateTimein the givenlocale.
daysinmonth(dt::TimeType) → Int¶Returns the number of days in the month of
dt. Value will be 28, 29, 30, or 31.
isleapyear(dt::TimeType) → Bool¶Returns
trueif the year ofdtis a leap year.
dayofyear(dt::TimeType) → Int¶Returns the day of the year for
dtwith January 1st being day 1.
daysinyear(dt::TimeType) → Int¶Returns 366 if the year of
dtis a leap year, otherwise returns 365.
quarterofyear(dt::TimeType) → Int¶Returns the quarter that
dtresides in. Range of value is 1:4.
dayofquarter(dt::TimeType) → Int¶Returns the day of the current quarter of
dt. Range of value is 1:92.
Adjuster Functions¶
trunc(dt::TimeType, ::Type{Period}) → TimeType¶Truncates the value of
dtaccording to the providedPeriodtype. E.g. ifdtis1996-01-01T12:30:00, thentrunc(dt,Day)==1996-01-01T00:00:00.
firstdayofweek(dt::TimeType) → TimeType¶Adjusts
dtto the Monday of its week.
lastdayofweek(dt::TimeType) → TimeType¶Adjusts
dtto the Sunday of its week.
firstdayofmonth(dt::TimeType) → TimeType¶Adjusts
dtto the first day of its month.
lastdayofmonth(dt::TimeType) → TimeType¶Adjusts
dtto the last day of its month.
firstdayofyear(dt::TimeType) → TimeType¶Adjusts
dtto the first day of its year.
lastdayofyear(dt::TimeType) → TimeType¶Adjusts
dtto the last day of its year.
firstdayofquarter(dt::TimeType) → TimeType¶Adjusts
dtto the first day of its quarter.
lastdayofquarter(dt::TimeType) → TimeType¶Adjusts
dtto the last day of its quarter.
tonext(dt::TimeType, dow::Int;same::Bool=false) → TimeType¶Adjusts
dtto the next day of week corresponding todowwith1=Monday,2=Tuesday,etc. Settingsame=trueallows the currentdtto be considered as the nextdow, allowing for no adjustment to occur.
toprev(dt::TimeType, dow::Int;same::Bool=false) → TimeType¶Adjusts
dtto the previous day of week corresponding todowwith1=Monday,2=Tuesday,etc. Settingsame=trueallows the currentdtto be considered as the previousdow, allowing for no adjustment to occur.
tofirst(dt::TimeType, dow::Int;of=Month) → TimeType¶Adjusts
dtto the firstdowof its month. Alternatively,of=Yearwill adjust to the firstdowof the year.
tolast(dt::TimeType, dow::Int;of=Month) → TimeType¶Adjusts
dtto the lastdowof its month. Alternatively,of=Yearwill adjust to the lastdowof the year.
tonext(func::Function, dt::TimeType;step=Day(1), negate=false, limit=10000, same=false) → TimeTypeAdjusts
dtby iterating at mostlimititerations bystepincrements untilfuncreturnstrue.funcmust take a singleTimeTypeargument and return aBool.sameallowsdtto be considered in satisfyingfunc.negatewill make the adjustment process terminate whenfuncreturnsfalseinstead oftrue.
toprev(func::Function, dt::TimeType;step=Day(-1), negate=false, limit=10000, same=false) → TimeTypeAdjusts
dtby iterating at mostlimititerations bystepincrements untilfuncreturnstrue.funcmust take a singleTimeTypeargument and return aBool.sameallowsdtto be considered in satisfyingfunc.negatewill make the adjustment process terminate whenfuncreturnsfalseinstead oftrue.
recur{T<:TimeType}(func::Function, dr::StepRange{T};negate=false, limit=10000) → Vector{T}¶functakes a single TimeType argument and returns aBoolindicating whether the input should be “included” in the final set.recurappliesfuncover each element in the range ofdr, including those elements for whichfuncreturnstruein the resulting Array, unlessnegate=true, then only elements wherefuncreturnsfalseare included.
Periods¶
Year(v)Month(v)Week(v)Day(v)Hour(v)Minute(v)Second(v)Millisecond(v)Construct a
Periodtype with the givenvvalue. Input must be losslessly convertible to anInt64.
CompoundPeriod(periods) → CompoundPeriodConstruct a
CompoundPeriodfrom aVectorofPeriods. The constructor will automatically simplify the periods into a canonical form according to the following rules:- All
Periods of the same type will be added together - Any
Periodlarge enough be partially representable by a coarserPeriodwill be broken into multiplePeriods (eg.Hour(30)becomesDay(1)+Hour(6)) Periods with opposite signs will be combined when possible (eg.Hour(1)-Day(1)becomes-Hour(23))
Due to the canonicalization,
CompoundPeriodis also useful for converting time periods into more human-comprehensible forms.Examples
julia>Dates.CompoundPeriod([Dates.Hour(12),Dates.Hour(13)])1day,1hourjulia>Dates.CompoundPeriod([Dates.Hour(-1),Dates.Minute(1)])-59minutesjulia>Dates.CompoundPeriod([Dates.Month(1),Dates.Week(-2)])1month,-2weeksjulia>Dates.CompoundPeriod(Dates.Minute(50000)))4weeks,6days,17hours,20minutes
- All
default(p::Period) → Period¶Returns a sensible “default” value for the input Period by returning
one(p)for Year, Month, and Day, andzero(p)for Hour, Minute, Second, and Millisecond.
Rounding Functions¶
Date and DateTime values can be rounded to a specified resolution (e.g., 1 month
or 15 minutes) with floor, ceil, or round.
floor(dt::TimeType, p::Period) → TimeType¶Returns the nearest
DateorDateTimeless than or equal todtat resolutionp.For convenience,
pmay be a type instead of a value:floor(dt,Dates.Hour)is a shortcut forfloor(dt,Dates.Hour(1)).julia>floor(Date(1985,8,16),Dates.Month)1985-08-01julia>floor(DateTime(2013,2,13,0,31,20),Dates.Minute(15))2013-02-13T00:30:00julia>floor(DateTime(2016,8,6,12,0,0),Dates.Day)2016-08-06T00:00:00
ceil(dt::TimeType, p::Period) → TimeType¶Returns the nearest
DateorDateTimegreater than or equal todtat resolutionp.For convenience,
pmay be a type instead of a value:ceil(dt,Dates.Hour)is a shortcut forceil(dt,Dates.Hour(1)).julia>ceil(Date(1985,8,16),Dates.Month)1985-09-01julia>ceil(DateTime(2013,2,13,0,31,20),Dates.Minute(15))2013-02-13T00:45:00julia>ceil(DateTime(2016,8,6,12,0,0),Dates.Day)2016-08-07T00:00:00
round(dt::TimeType, p::Period[, r::RoundingMode]) → TimeType¶Returns the
DateorDateTimenearest todtat resolutionp. By default (RoundNearestTiesUp), ties (e.g., rounding 9:30 to the nearest hour) will be rounded up.For convenience,
pmay be a type instead of a value:round(dt,Dates.Hour)is a shortcut forround(dt,Dates.Hour(1)).julia>round(Date(1985,8,16),Dates.Month)1985-08-01julia>round(DateTime(2013,2,13,0,31,20),Dates.Minute(15))2013-02-13T00:30:00julia>round(DateTime(2016,8,6,12,0,0),Dates.Day)2016-08-07T00:00:00
Valid rounding modes for
round(::TimeType,::Period,::RoundingMode)areRoundNearestTiesUp(default),RoundDown(floor), andRoundUp(ceil).
The following functions are not exported:
floorceil(dt::TimeType, p::Period) → (TimeType, TimeType)¶Simultaneously return the
floorandceilof aDateorDateTimeat resolutionp. More efficient than calling bothfloorandceilindividually.
epochdays2date(days) → Date¶Takes the number of days since the rounding epoch (
0000-01-01T00:00:00) and returns the correspondingDate.
epochms2datetime(milliseconds) → DateTime¶Takes the number of milliseconds since the rounding epoch (
0000-01-01T00:00:00) and returns the correspondingDateTime.
date2epochdays(dt::Date) → Int64¶Takes the given
Dateand returns the number of days since the rounding epoch (0000-01-01T00:00:00) as anInt64.
datetime2epochms(dt::DateTime) → Int64¶Takes the given
DateTimeand returns the number of milliseconds since the rounding epoch (0000-01-01T00:00:00) as anInt64.
Conversion Functions¶
today() → Date¶Returns the date portion of
now().
unix2datetime(x) → DateTime¶Takes the number of seconds since unix epoch
1970-01-01T00:00:00and converts to the correspondingDateTime.
datetime2unix(dt::DateTime) → Float64¶Takes the given
DateTimeand returns the number of seconds since the unix epoch1970-01-01T00:00:00as aFloat64.
julian2datetime(julian_days) → DateTime¶Takes the number of Julian calendar days since epoch
-4713-11-24T12:00:00and returns the correspondingDateTime.
datetime2julian(dt::DateTime) → Float64¶Takes the given
DateTimeand returns the number of Julian calendar days since the julian epoch-4713-11-24T12:00:00as aFloat64.
rata2datetime(days) → DateTime¶Takes the number of Rata Die days since epoch
0000-12-31T00:00:00and returns the correspondingDateTime.
datetime2rata(dt::TimeType) → Int64¶Returns the number of Rata Die days since epoch from the given
DateorDateTime.
Constants¶
Days of the Week:
| Variable | Abbr. | Value (Int) |
|---|---|---|
Monday | Mon | 1 |
Tuesday | Tue | 2 |
Wednesday | Wed | 3 |
Thursday | Thu | 4 |
Friday | Fri | 5 |
Saturday | Sat | 6 |
Sunday | Sun | 7 |
Months of the Year:
| Variable | Abbr. | Value (Int) |
|---|---|---|
January | Jan | 1 |
February | Feb | 2 |
March | Mar | 3 |
April | Apr | 4 |
May | May | 5 |
June | Jun | 6 |
July | Jul | 7 |
August | Aug | 8 |
September | Sep | 9 |
October | Oct | 10 |
November | Nov | 11 |
December | Dec | 12 |