Dates

The Dates module provides two types for working with dates: Date and DateTime, representing day and millisecond precision, respectively; both are subtypes of the abstract TimeType. The motivation for distinct types is simple: some operations are much simpler, both in terms of code and mental reasoning, when the complexities of greater precision don’t have to be dealt with. For example, since the Date type only resolves to the precision of a single date (i.e. no hours, minutes, or seconds), normal considerations for time zones, daylight savings/summer time, and leap seconds are unnecessary and avoided.

Both Date and DateTime are basically immutable Int64 wrappers. The single instant field of either type is actually a UTInstant{P} type, which represents a continuously increasing machine timeline based on the UT second [1]. The DateTime type is not aware of time zones (naive, in Python parlance), analogous to a LocalDateTime in Java 8. Additional time zone functionality can be added through the TimeZones.jl package, which compiles the IANA time zone database. Both Date and DateTime are based on the ISO 8601 standard, which follows the proleptic Gregorian calendar. One note is that the ISO 8601 standard is particular about BC/BCE dates. In general, the last day of the BC/BCE era, 1-12-31 BC/BCE, was followed by 1-1-1 AD/CE, thus no year zero exists. The ISO standard, however, states that 1 BC/BCE is year zero, so 0000-12-31 is the day before 0001-01-01, and year -0001 (yes, negative one for the year) is 2 BC/BCE, year -0002 is 3 BC/BCE, etc.

Constructors

Date and DateTime types can be constructed by integer or Period types, by parsing, or through adjusters (more on those later):

  1. julia> DateTime(2013)
  2. 2013-01-01T00:00:00
  3. julia> DateTime(2013,7)
  4. 2013-07-01T00:00:00
  5. julia> DateTime(2013,7,1)
  6. 2013-07-01T00:00:00
  7. julia> DateTime(2013,7,1,12)
  8. 2013-07-01T12:00:00
  9. julia> DateTime(2013,7,1,12,30)
  10. 2013-07-01T12:30:00
  11. julia> DateTime(2013,7,1,12,30,59)
  12. 2013-07-01T12:30:59
  13. julia> DateTime(2013,7,1,12,30,59,1)
  14. 2013-07-01T12:30:59.001
  15. julia> Date(2013)
  16. 2013-01-01
  17. julia> Date(2013,7)
  18. 2013-07-01
  19. julia> Date(2013,7,1)
  20. 2013-07-01
  21. julia> Date(Dates.Year(2013),Dates.Month(7),Dates.Day(1))
  22. 2013-07-01
  23. julia> Date(Dates.Month(7),Dates.Year(2013))
  24. 2013-07-01

Date or DateTime parsing is accomplished by the use of format strings. Format strings work by the notion of defining delimited or fixed-width “slots” that contain a period to parse and passing the text to parse and format string to a Date or DateTime constructor, of the form Date("2015-01-01",dateformat"y-m-d") or DateTime("20150101",dateformat"yyyymmdd").

Delimited slots are marked by specifying the delimiter the parser should expect between two subsequent periods; so "y-m-d" lets the parser know that between the first and second slots in a date string like "2014-07-16", it should find the - character. The y, m, and d characters let the parser know which periods to parse in each slot.

As in the case of constructors above such as Date(2013), delimited DateFormats allow for missing parts of dates and times so long as the preceding parts are given. The other parts are given the usual default values. For example, Date("1981-03", dateformat"y-m-d") returns 1981-03-01, whilst Date("31/12", dateformat"d/m/y") gives 0001-12-31. (Note that the default year is 1 AD/CE.) Consequently, an empty string will always return 0001-01-01 for Dates, and 0001-01-01T00:00:00.000 for DateTimes.

Fixed-width slots are specified by repeating the period character the number of times corresponding to the width with no delimiter between characters. So dateformat"yyyymmdd" would correspond to a date string like "20140716". The parser distinguishes a fixed-width slot by the absence of a delimiter, noting the transition "yyyymm" from one period character to the next.

Support for text-form month parsing is also supported through the u and U characters, for abbreviated and full-length month names, respectively. By default, only English month names are supported, so u corresponds to “Jan”, “Feb”, “Mar”, etc. And U corresponds to “January”, “February”, “March”, etc. Similar to other name=>value mapping functions dayname and monthname, custom locales can be loaded by passing in the locale=>Dict{String,Int} mapping to the MONTHTOVALUEABBR and MONTHTOVALUE dicts for abbreviated and full-name month names, respectively.

The above examples used the dateformat"" string macro. This macro creates a DateFormat object once when the macro is expanded and uses the same DateFormat object even if a code snippet is run multiple times.

  1. julia> for i = 1:10^5
  2. Date("2015-01-01", dateformat"y-m-d")
  3. end

Or you can create the DateFormat object explicitly:

  1. julia> df = DateFormat("y-m-d");
  2. julia> dt = Date("2015-01-01",df)
  3. 2015-01-01
  4. julia> dt2 = Date("2015-01-02",df)
  5. 2015-01-02

Alternatively, use broadcasting:

  1. julia> years = ["2015", "2016"];
  2. julia> Date.(years, DateFormat("yyyy"))
  3. 2-element Vector{Date}:
  4. 2015-01-01
  5. 2016-01-01

For convenience, you may pass the format string directly (e.g., Date("2015-01-01","y-m-d")), although this form incurs performance costs if you are parsing the same format repeatedly, as it internally creates a new DateFormat object each time.

As well as via the constructors, a Date or DateTime can be constructed from strings using the parse and tryparse functions, but with an optional third argument of type DateFormat specifying the format; for example, parse(Date, "06.23.2013", dateformat"m.d.y"), or tryparse(DateTime, "1999-12-31T23:59:59") which uses the default format. The notable difference between the functions is that with tryparse, an error is not thrown if the string is in an invalid format; instead nothing is returned. Note however that as with the constructors above, empty date and time parts assume default values and consequently an empty string ("") is valid for any DateFormat, giving for example a Date of 0001-01-01. Code relying on parse or tryparse for Date and DateTime parsing should therefore also check whether parsed strings are empty before using the result.

A full suite of parsing and formatting tests and examples is available in stdlib/Dates/test/io.jl.

Durations/Comparisons

Finding the length of time between two Date or DateTime is straightforward given their underlying representation as UTInstant{Day} and UTInstant{Millisecond}, respectively. The difference between Date is returned in the number of Day, and DateTime in the number of Millisecond. Similarly, comparing TimeType is a simple matter of comparing the underlying machine instants (which in turn compares the internal Int64 values).

  1. julia> dt = Date(2012,2,29)
  2. 2012-02-29
  3. julia> dt2 = Date(2000,2,1)
  4. 2000-02-01
  5. julia> dump(dt)
  6. Date
  7. instant: Dates.UTInstant{Day}
  8. periods: Day
  9. value: Int64 734562
  10. julia> dump(dt2)
  11. Date
  12. instant: Dates.UTInstant{Day}
  13. periods: Day
  14. value: Int64 730151
  15. julia> dt > dt2
  16. true
  17. julia> dt != dt2
  18. true
  19. julia> dt + dt2
  20. ERROR: MethodError: no method matching +(::Date, ::Date)
  21. [...]
  22. julia> dt * dt2
  23. ERROR: MethodError: no method matching *(::Date, ::Date)
  24. [...]
  25. julia> dt / dt2
  26. ERROR: MethodError: no method matching /(::Date, ::Date)
  27. julia> dt - dt2
  28. 4411 days
  29. julia> dt2 - dt
  30. -4411 days
  31. julia> dt = DateTime(2012,2,29)
  32. 2012-02-29T00:00:00
  33. julia> dt2 = DateTime(2000,2,1)
  34. 2000-02-01T00:00:00
  35. julia> dt - dt2
  36. 381110400000 milliseconds

Accessor Functions

Because the Date and DateTime types are stored as single Int64 values, date parts or fields can be retrieved through accessor functions. The lowercase accessors return the field as an integer:

  1. julia> t = Date(2014, 1, 31)
  2. 2014-01-31
  3. julia> Dates.year(t)
  4. 2014
  5. julia> Dates.month(t)
  6. 1
  7. julia> Dates.week(t)
  8. 5
  9. julia> Dates.day(t)
  10. 31

While propercase return the same value in the corresponding Period type:

  1. julia> Dates.Year(t)
  2. 2014 years
  3. julia> Dates.Day(t)
  4. 31 days

Compound methods are provided because it is more efficient to access multiple fields at the same time than individually:

  1. julia> Dates.yearmonth(t)
  2. (2014, 1)
  3. julia> Dates.monthday(t)
  4. (1, 31)
  5. julia> Dates.yearmonthday(t)
  6. (2014, 1, 31)

One may also access the underlying UTInstant or integer value:

  1. julia> dump(t)
  2. Date
  3. instant: Dates.UTInstant{Day}
  4. periods: Day
  5. value: Int64 735264
  6. julia> t.instant
  7. Dates.UTInstant{Day}(Day(735264))
  8. julia> Dates.value(t)
  9. 735264

Query Functions

Query functions provide calendrical information about a TimeType. They include information about the day of the week:

  1. julia> t = Date(2014, 1, 31)
  2. 2014-01-31
  3. julia> Dates.dayofweek(t)
  4. 5
  5. julia> Dates.dayname(t)
  6. "Friday"
  7. julia> Dates.dayofweekofmonth(t) # 5th Friday of January
  8. 5

Month of the year:

  1. julia> Dates.monthname(t)
  2. "January"
  3. julia> Dates.daysinmonth(t)
  4. 31

As well as information about the TimeType‘s year and quarter:

  1. julia> Dates.isleapyear(t)
  2. false
  3. julia> Dates.dayofyear(t)
  4. 31
  5. julia> Dates.quarterofyear(t)
  6. 1
  7. julia> Dates.dayofquarter(t)
  8. 31

The dayname and monthname methods can also take an optional locale keyword that can be used to return the name of the day or month of the year for other languages/locales. There are also versions of these functions returning the abbreviated names, namely dayabbr and monthabbr. First the mapping is loaded into the LOCALES variable:

  1. julia> french_months = ["janvier", "février", "mars", "avril", "mai", "juin",
  2. "juillet", "août", "septembre", "octobre", "novembre", "décembre"];
  3. julia> french_monts_abbrev = ["janv","févr","mars","avril","mai","juin",
  4. "juil","août","sept","oct","nov","déc"];
  5. julia> french_days = ["lundi","mardi","mercredi","jeudi","vendredi","samedi","dimanche"];
  6. julia> Dates.LOCALES["french"] = Dates.DateLocale(french_months, french_monts_abbrev, french_days, [""]);

The above mentioned functions can then be used to perform the queries:

  1. julia> Dates.dayname(t;locale="french")
  2. "vendredi"
  3. julia> Dates.monthname(t;locale="french")
  4. "janvier"
  5. julia> Dates.monthabbr(t;locale="french")
  6. "janv"

Since the abbreviated versions of the days are not loaded, trying to use the function dayabbr will error.

  1. julia> Dates.dayabbr(t;locale="french")
  2. ERROR: BoundsError: attempt to access 1-element Vector{String} at index [5]
  3. Stacktrace:
  4. [...]

TimeType-Period Arithmetic

It’s good practice when using any language/date framework to be familiar with how date-period arithmetic is handled as there are some tricky issues to deal with (though much less so for day-precision types).

The Dates module approach tries to follow the simple principle of trying to change as little as possible when doing Period arithmetic. This approach is also often known as calendrical arithmetic or what you would probably guess if someone were to ask you the same calculation in a conversation. Why all the fuss about this? Let’s take a classic example: add 1 month to January 31st, 2014. What’s the answer? Javascript will say March 3 (assumes 31 days). PHP says March 2 (assumes 30 days). The fact is, there is no right answer. In the Dates module, it gives the result of February 28th. How does it figure that out? Consider the classic 7-7-7 gambling game in casinos.

Now just imagine that instead of 7-7-7, the slots are Year-Month-Day, or in our example, 2014-01-31. When you ask to add 1 month to this date, the month slot is incremented, so now we have 2014-02-31. Then the day number is checked if it is greater than the last valid day of the new month; if it is (as in the case above), the day number is adjusted down to the last valid day (28). What are the ramifications with this approach? Go ahead and add another month to our date, 2014-02-28 + Month(1) == 2014-03-28. What? Were you expecting the last day of March? Nope, sorry, remember the 7-7-7 slots. As few slots as possible are going to change, so we first increment the month slot by 1, 2014-03-28, and boom, we’re done because that’s a valid date. On the other hand, if we were to add 2 months to our original date, 2014-01-31, then we end up with 2014-03-31, as expected. The other ramification of this approach is a loss in associativity when a specific ordering is forced (i.e. adding things in different orders results in different outcomes). For example:

  1. julia> (Date(2014,1,29)+Dates.Day(1)) + Dates.Month(1)
  2. 2014-02-28
  3. julia> (Date(2014,1,29)+Dates.Month(1)) + Dates.Day(1)
  4. 2014-03-01

What’s going on there? In the first line, we’re adding 1 day to January 29th, which results in 2014-01-30; then we add 1 month, so we get 2014-02-30, which then adjusts down to 2014-02-28. In the second example, we add 1 month first, where we get 2014-02-29, which adjusts down to 2014-02-28, and then add 1 day, which results in 2014-03-01. One design principle that helps in this case is that, in the presence of multiple Periods, the operations will be ordered by the Periods’ types, not their value or positional order; this means Year will always be added first, then Month, then Week, etc. Hence the following does result in associativity and Just Works:

  1. julia> Date(2014,1,29) + Dates.Day(1) + Dates.Month(1)
  2. 2014-03-01
  3. julia> Date(2014,1,29) + Dates.Month(1) + Dates.Day(1)
  4. 2014-03-01

Tricky? Perhaps. What is an innocent Dates user to do? The bottom line is to be aware that explicitly forcing a certain associativity, when dealing with months, may lead to some unexpected results, but otherwise, everything should work as expected. Thankfully, that’s pretty much the extent of the odd cases in date-period arithmetic when dealing with time in UT (avoiding the “joys” of dealing with daylight savings, leap seconds, etc.).

As a bonus, all period arithmetic objects work directly with ranges:

  1. julia> dr = Date(2014,1,29):Day(1):Date(2014,2,3)
  2. Date("2014-01-29"):Day(1):Date("2014-02-03")
  3. julia> collect(dr)
  4. 6-element Vector{Date}:
  5. 2014-01-29
  6. 2014-01-30
  7. 2014-01-31
  8. 2014-02-01
  9. 2014-02-02
  10. 2014-02-03
  11. julia> dr = Date(2014,1,29):Dates.Month(1):Date(2014,07,29)
  12. Date("2014-01-29"):Month(1):Date("2014-07-29")
  13. julia> collect(dr)
  14. 7-element Vector{Date}:
  15. 2014-01-29
  16. 2014-02-28
  17. 2014-03-29
  18. 2014-04-29
  19. 2014-05-29
  20. 2014-06-29
  21. 2014-07-29

Adjuster Functions

As convenient as date-period arithmetic is, often the kinds of calculations needed on dates take on a calendrical or temporal nature rather than a fixed number of periods. Holidays are a perfect example; most follow rules such as “Memorial Day = Last Monday of May”, or “Thanksgiving = 4th Thursday of November”. These kinds of temporal expressions deal with rules relative to the calendar, like first or last of the month, next Tuesday, or the first and third Wednesdays, etc.

The Dates module provides the adjuster API through several convenient methods that aid in simply and succinctly expressing temporal rules. The first group of adjuster methods deal with the first and last of weeks, months, quarters, and years. They each take a single TimeType as input and return or adjust to the first or last of the desired period relative to the input.

  1. julia> Dates.firstdayofweek(Date(2014,7,16)) # Adjusts the input to the Monday of the input's week
  2. 2014-07-14
  3. julia> Dates.lastdayofmonth(Date(2014,7,16)) # Adjusts to the last day of the input's month
  4. 2014-07-31
  5. julia> Dates.lastdayofquarter(Date(2014,7,16)) # Adjusts to the last day of the input's quarter
  6. 2014-09-30

The next two higher-order methods, tonext, and toprev, generalize working with temporal expressions by taking a DateFunction as first argument, along with a starting TimeType. A DateFunction is just a function, usually anonymous, that takes a single TimeType as input and returns a Bool, true indicating a satisfied adjustment criterion. For example:

  1. julia> istuesday = x->Dates.dayofweek(x) == Dates.Tuesday; # Returns true if the day of the week of x is Tuesday
  2. julia> Dates.tonext(istuesday, Date(2014,7,13)) # 2014-07-13 is a Sunday
  3. 2014-07-15
  4. julia> Dates.tonext(Date(2014,7,13), Dates.Tuesday) # Convenience method provided for day of the week adjustments
  5. 2014-07-15

This is useful with the do-block syntax for more complex temporal expressions:

  1. julia> Dates.tonext(Date(2014,7,13)) do x
  2. # Return true on the 4th Thursday of November (Thanksgiving)
  3. Dates.dayofweek(x) == Dates.Thursday &&
  4. Dates.dayofweekofmonth(x) == 4 &&
  5. Dates.month(x) == Dates.November
  6. end
  7. 2014-11-27

The Base.filter method can be used to obtain all valid dates/moments in a specified range:

  1. # Pittsburgh street cleaning; Every 2nd Tuesday from April to November
  2. # Date range from January 1st, 2014 to January 1st, 2015
  3. julia> dr = Dates.Date(2014):Day(1):Dates.Date(2015);
  4. julia> filter(dr) do x
  5. Dates.dayofweek(x) == Dates.Tue &&
  6. Dates.April <= Dates.month(x) <= Dates.Nov &&
  7. Dates.dayofweekofmonth(x) == 2
  8. end
  9. 8-element Vector{Date}:
  10. 2014-04-08
  11. 2014-05-13
  12. 2014-06-10
  13. 2014-07-08
  14. 2014-08-12
  15. 2014-09-09
  16. 2014-10-14
  17. 2014-11-11

Additional examples and tests are available in stdlib/Dates/test/adjusters.jl.

Period Types

Periods are a human view of discrete, sometimes irregular durations of time. Consider 1 month; it could represent, in days, a value of 28, 29, 30, or 31 depending on the year and month context. Or a year could represent 365 or 366 days in the case of a leap year. Period types are simple Int64 wrappers and are constructed by wrapping any Int64 convertible type, i.e. Year(1) or Month(3.0). Arithmetic between Period of the same type behave like integers, and limited Period-Real arithmetic is available. You can extract the underlying integer with Dates.value.

  1. julia> y1 = Dates.Year(1)
  2. 1 year
  3. julia> y2 = Dates.Year(2)
  4. 2 years
  5. julia> y3 = Dates.Year(10)
  6. 10 years
  7. julia> y1 + y2
  8. 3 years
  9. julia> div(y3,y2)
  10. 5
  11. julia> y3 - y2
  12. 8 years
  13. julia> y3 % y2
  14. 0 years
  15. julia> div(y3,3) # mirrors integer division
  16. 3 years
  17. julia> Dates.value(Dates.Millisecond(10))
  18. 10

Rounding

Date and DateTime values can be rounded to a specified resolution (e.g., 1 month or 15 minutes) with floor, ceil, or round:

  1. julia> floor(Date(1985, 8, 16), Dates.Month)
  2. 1985-08-01
  3. julia> ceil(DateTime(2013, 2, 13, 0, 31, 20), Dates.Minute(15))
  4. 2013-02-13T00:45:00
  5. julia> round(DateTime(2016, 8, 6, 20, 15), Dates.Day)
  6. 2016-08-07T00:00:00

Unlike the numeric round method, which breaks ties toward the even number by default, the TimeTyperound method uses the RoundNearestTiesUp rounding mode. (It’s difficult to guess what breaking ties to nearest “even” TimeType would entail.) Further details on the available RoundingMode s can be found in the API reference.

Rounding should generally behave as expected, but there are a few cases in which the expected behaviour is not obvious.

Rounding Epoch

In many cases, the resolution specified for rounding (e.g., Dates.Second(30)) divides evenly into the next largest period (in this case, Dates.Minute(1)). But rounding behaviour in cases in which this is not true may lead to confusion. What is the expected result of rounding a DateTime to the nearest 10 hours?

  1. julia> round(DateTime(2016, 7, 17, 11, 55), Dates.Hour(10))
  2. 2016-07-17T12:00:00

That may seem confusing, given that the hour (12) is not divisible by 10. The reason that 2016-07-17T12:00:00 was chosen is that it is 17,676,660 hours after 0000-01-01T00:00:00, and 17,676,660 is divisible by 10.

As Julia Date and DateTime values are represented according to the ISO 8601 standard, 0000-01-01T00:00:00 was chosen as base (or “rounding epoch”) from which to begin the count of days (and milliseconds) used in rounding calculations. (Note that this differs slightly from Julia’s internal representation of Date s using Rata Die notation; but since the ISO 8601 standard is most visible to the end user, 0000-01-01T00:00:00 was chosen as the rounding epoch instead of the 0000-12-31T00:00:00 used internally to minimize confusion.)

The only exception to the use of 0000-01-01T00:00:00 as the rounding epoch is when rounding to weeks. Rounding to the nearest week will always return a Monday (the first day of the week as specified by ISO 8601). For this reason, we use 0000-01-03T00:00:00 (the first day of the first week of year 0000, as defined by ISO 8601) as the base when rounding to a number of weeks.

Here is a related case in which the expected behaviour is not necessarily obvious: What happens when we round to the nearest P(2), where P is a Period type? In some cases (specifically, when P <: Dates.TimePeriod) the answer is clear:

  1. julia> round(DateTime(2016, 7, 17, 8, 55, 30), Dates.Hour(2))
  2. 2016-07-17T08:00:00
  3. julia> round(DateTime(2016, 7, 17, 8, 55, 30), Dates.Minute(2))
  4. 2016-07-17T08:56:00

This seems obvious, because two of each of these periods still divides evenly into the next larger order period. But in the case of two months (which still divides evenly into one year), the answer may be surprising:

  1. julia> round(DateTime(2016, 7, 17, 8, 55, 30), Dates.Month(2))
  2. 2016-07-01T00:00:00

Why round to the first day in July, even though it is month 7 (an odd number)? The key is that months are 1-indexed (the first month is assigned 1), unlike hours, minutes, seconds, and milliseconds (the first of which are assigned 0).

This means that rounding a DateTime to an even multiple of seconds, minutes, hours, or years (because the ISO 8601 specification includes a year zero) will result in a DateTime with an even value in that field, while rounding a DateTime to an even multiple of months will result in the months field having an odd value. Because both months and years may contain an irregular number of days, whether rounding to an even number of days will result in an even value in the days field is uncertain.

See the API reference for additional information on methods exported from the Dates module.

API reference

Dates and Time Types

Dates.Period — Type

  1. Period
  2. Year
  3. Quarter
  4. Month
  5. Week
  6. Day
  7. Hour
  8. Minute
  9. Second
  10. Millisecond
  11. Microsecond
  12. Nanosecond

Period types represent discrete, human representations of time.

source

Dates.CompoundPeriod — Type

  1. CompoundPeriod

A CompoundPeriod is 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 a CompoundPeriod. In fact, a CompoundPeriod is automatically generated by addition of different period types, e.g. Year(1) + Day(1) produces a CompoundPeriod result.

source

Dates.Instant — Type

  1. Instant

Instant types represent integer-based, machine representations of time as continuous timelines starting from an epoch.

source

Dates.UTInstant — Type

  1. UTInstant{T}

The UTInstant represents a machine timeline based on UT time (1 day = one revolution of the earth). The T is a Period parameter that indicates the resolution or precision of the instant.

source

Dates.TimeType — Type

  1. TimeType

TimeType types wrap Instant machine instances to provide human representations of the machine instant. Time, DateTime and Date are subtypes of TimeType.

source

Dates.DateTime — Type

  1. DateTime

DateTime wraps a UTInstant{Millisecond} and interprets it according to the proleptic Gregorian calendar.

source

Dates.Date — Type

  1. Date

Date wraps a UTInstant{Day} and interprets it according to the proleptic Gregorian calendar.

source

Dates.Time — Type

  1. Time

Time wraps a Nanosecond and represents a specific moment in a 24-hour day.

source

Dates.TimeZone — Type

  1. TimeZone

Geographic zone generally based on longitude determining what the time is at a certain location. Some time zones observe daylight savings (eg EST -> EDT). For implementations and more support, see the TimeZones.jl package

source

Dates.UTC — Type

  1. UTC

UTC, or Coordinated Universal Time, is the TimeZone from which all others are measured. It is associated with the time at 0° longitude. It is not adjusted for daylight savings.

source

Dates Functions

Dates.DateTime — Method

  1. DateTime(y, [m, d, h, mi, s, ms]) -> DateTime

Construct a DateTime type by parts. Arguments must be convertible to Int64.

source

Dates.DateTime — Method

  1. DateTime(periods::Period...) -> DateTime

Construct a DateTime type by Period type parts. Arguments may be in any order. DateTime parts not provided will default to the value of Dates.default(period).

source

Dates.DateTime — Method

  1. DateTime(f::Function, y[, m, d, h, mi, s]; step=Day(1), limit=10000) -> DateTime

Create a DateTime through the adjuster API. The starting point will be constructed from the provided y, m, d... arguments, and will be adjusted until f::Function returns true. The step size in adjusting can be provided manually through the step keyword. limit provides a limit to the max number of iterations the adjustment API will pursue before throwing an error (in the case that f::Function is never satisfied).

Examples

  1. julia> DateTime(dt -> Dates.second(dt) == 40, 2010, 10, 20, 10; step = Dates.Second(1))
  2. 2010-10-20T10:00:40
  3. julia> DateTime(dt -> Dates.hour(dt) == 20, 2010, 10, 20, 10; step = Dates.Hour(1), limit = 5)
  4. ERROR: ArgumentError: Adjustment limit reached: 5 iterations
  5. Stacktrace:
  6. [...]

source

Dates.DateTime — Method

  1. DateTime(dt::Date) -> DateTime

Convert a Date to a DateTime. The hour, minute, second, and millisecond parts of the new DateTime are assumed to be zero.

source

Dates.DateTime — Method

  1. DateTime(dt::AbstractString, format::AbstractString; locale="english") -> DateTime

Construct a DateTime by parsing the dt date time string following the pattern given in the format string (see DateFormat for syntax).

Note

This method creates a DateFormat object each time it is called. It is recommended that you create a DateFormat object instead and use that as the second argument to avoid performance loss when using the same format repeatedly.

Example

  1. julia> DateTime("2020-01-01", "yyyy-mm-dd")
  2. 2020-01-01T00:00:00
  3. julia> a = ("2020-01-01", "2020-01-02");
  4. julia> [DateTime(d, dateformat"yyyy-mm-dd") for d a] # preferred
  5. 2-element Vector{DateTime}:
  6. 2020-01-01T00:00:00
  7. 2020-01-02T00:00:00

source

Dates.format — Method

  1. format(dt::TimeType, format::AbstractString; locale="english") -> AbstractString

Construct a string by using a TimeType object and applying the provided format. The following character codes can be used to construct the format string:

CodeExamplesComment
y6Numeric year with a fixed width
Y1996Numeric year with a minimum width
m1, 12Numeric month with a minimum width
uJanMonth name shortened to 3-chars according to the locale
UJanuaryFull month name according to the locale keyword
d1, 31Day of the month with a minimum width
H0, 23Hour (24-hour clock) with a minimum width
M0, 59Minute with a minimum width
S0, 59Second with a minimum width
s000, 500Millisecond with a minimum width of 3
eMon, TueAbbreviated days of the week
EMondayFull day of week name

The number of sequential code characters indicate the width of the code. A format of yyyy-mm specifies that the code y should have a width of four while m a 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 format you can use any non-code characters as a separator. For example to generate the string “1996-01-15T00:00:00” you could use format: “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”.

source

Dates.DateFormat — Type

  1. DateFormat(format::AbstractString, locale="english") -> DateFormat

Construct a date formatting object that can be used for parsing date strings or formatting a date object as a string. The following character codes can be used to construct the format string:

CodeMatchesComment
y1996, 96Returns year of 1996, 0096
Y1996, 96Returns year of 1996, 0096. Equivalent to y
m1, 01Matches 1 or 2-digit months
uJanMatches abbreviated months according to the locale keyword
UJanuaryMatches full month names according to the locale keyword
d1, 01Matches 1 or 2-digit days
H00Matches hours (24-hour clock)
I00For outputting hours with 12-hour clock
M00Matches minutes
S00Matches seconds
s.500Matches milliseconds
eMon, TuesMatches abbreviated days of the week
EMondayMatches full name days of the week
pAMMatches AM/PM (case-insensitive)
yyyymmdd19960101Matches fixed-width year, month, and day

Characters not listed above are normally treated as delimiters between date and time slots. For example a dt string of “1996-01-15T00:00:00.0” would have a format string 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”.

Note that 12:00AM corresponds 00:00 (midnight), and 12:00PM corresponds to 12:00 (noon). When parsing a time with a p specifier, any hour (either H or I) is interpreted as as a 12-hour clock, so the I code is mainly useful for output.

Creating a DateFormat object is expensive. Whenever possible, create it once and use it many times or try the dateformat”” string macro. Using this macro creates the DateFormat object once at macro expansion time and reuses it later. There are also several pre-defined formatters, listed later.

See DateTime and format for how to use a DateFormat object to parse and write Date strings respectively.

source

Dates.@dateformat_str — Macro

  1. dateformat"Y-m-d H:M:S"

Create a DateFormat object. Similar to DateFormat("Y-m-d H:M:S") but creates the DateFormat object once during macro expansion.

See DateFormat for details about format specifiers.

source

Dates.DateTime — Method

  1. DateTime(dt::AbstractString, df::DateFormat=ISODateTimeFormat) -> DateTime

Construct a DateTime by parsing the dt date time string following the pattern given in the DateFormat object, or dateformat”yyyy-mm-ddTHH:MM:SS.s” if omitted.

Similar to DateTime(::AbstractString, ::AbstractString) but more efficient when repeatedly parsing similarly formatted date time strings with a pre-created DateFormat object.

source

Dates.Date — Method

  1. Date(y, [m, d]) -> Date

Construct a Date type by parts. Arguments must be convertible to Int64.

source

Dates.Date — Method

  1. Date(period::Period...) -> Date

Construct a Date type by Period type parts. Arguments may be in any order. Date parts not provided will default to the value of Dates.default(period).

source

Dates.Date — Method

  1. Date(f::Function, y[, m, d]; step=Day(1), limit=10000) -> Date

Create a Date through the adjuster API. The starting point will be constructed from the provided y, m, d arguments, and will be adjusted until f::Function returns true. The step size in adjusting can be provided manually through the step keyword. limit provides a limit to the max number of iterations the adjustment API will pursue before throwing an error (given that f::Function is never satisfied).

Examples

  1. julia> Date(date -> Dates.week(date) == 20, 2010, 01, 01)
  2. 2010-05-17
  3. julia> Date(date -> Dates.year(date) == 2010, 2000, 01, 01)
  4. 2010-01-01
  5. julia> Date(date -> Dates.month(date) == 10, 2000, 01, 01; limit = 5)
  6. ERROR: ArgumentError: Adjustment limit reached: 5 iterations
  7. Stacktrace:
  8. [...]

source

Dates.Date — Method

  1. Date(dt::DateTime) -> Date

Convert a DateTime to a Date. The hour, minute, second, and millisecond parts of the DateTime are truncated, so only the year, month and day parts are used in construction.

source

Dates.Date — Method

  1. Date(d::AbstractString, format::AbstractString; locale="english") -> Date

Construct a Date by parsing the d date string following the pattern given in the format string (see DateFormat for syntax).

Note

This method creates a DateFormat object each time it is called. It is recommended that you create a DateFormat object instead and use that as the second argument to avoid performance loss when using the same format repeatedly.

Example

  1. julia> Date("2020-01-01", "yyyy-mm-dd")
  2. 2020-01-01
  3. julia> a = ("2020-01-01", "2020-01-02");
  4. julia> [Date(d, dateformat"yyyy-mm-dd") for d a] # preferred
  5. 2-element Vector{Date}:
  6. 2020-01-01
  7. 2020-01-02

source

Dates.Date — Method

  1. Date(d::AbstractString, df::DateFormat=ISODateFormat) -> Date

Construct a Date by parsing the d date string following the pattern given in the DateFormat object, or dateformat”yyyy-mm-dd” if omitted.

Similar to Date(::AbstractString, ::AbstractString) but more efficient when repeatedly parsing similarly formatted date strings with a pre-created DateFormat object.

source

Dates.Time — Method

  1. Time(h, [mi, s, ms, us, ns]) -> Time

Construct a Time type by parts. Arguments must be convertible to Int64.

source

Dates.Time — Method

  1. Time(period::TimePeriod...) -> Time

Construct a Time type by Period type parts. Arguments may be in any order. Time parts not provided will default to the value of Dates.default(period).

source

Dates.Time — Method

  1. Time(f::Function, h, mi=0; step::Period=Second(1), limit::Int=10000)
  2. Time(f::Function, h, mi, s; step::Period=Millisecond(1), limit::Int=10000)
  3. Time(f::Function, h, mi, s, ms; step::Period=Microsecond(1), limit::Int=10000)
  4. Time(f::Function, h, mi, s, ms, us; step::Period=Nanosecond(1), limit::Int=10000)

Create a Time through the adjuster API. The starting point will be constructed from the provided h, mi, s, ms, us arguments, and will be adjusted until f::Function returns true. The step size in adjusting can be provided manually through the step keyword. limit provides a limit to the max number of iterations the adjustment API will pursue before throwing an error (in the case that f::Function is never satisfied). Note that the default step will adjust to allow for greater precision for the given arguments; i.e. if hour, minute, and second arguments are provided, the default step will be Millisecond(1) instead of Second(1).

Examples

  1. julia> Dates.Time(t -> Dates.minute(t) == 30, 20)
  2. 20:30:00
  3. julia> Dates.Time(t -> Dates.minute(t) == 0, 20)
  4. 20:00:00
  5. julia> Dates.Time(t -> Dates.hour(t) == 10, 3; limit = 5)
  6. ERROR: ArgumentError: Adjustment limit reached: 5 iterations
  7. Stacktrace:
  8. [...]

source

Dates.Time — Method

  1. Time(dt::DateTime) -> Time

Convert a DateTime to a Time. The hour, minute, second, and millisecond parts of the DateTime are used to create the new Time. Microsecond and nanoseconds are zero by default.

source

Dates.Time — Method

  1. Time(t::AbstractString, format::AbstractString; locale="english") -> Time

Construct a Time by parsing the t time string following the pattern given in the format string (see DateFormat for syntax).

Note

This method creates a DateFormat object each time it is called. It is recommended that you create a DateFormat object instead and use that as the second argument to avoid performance loss when using the same format repeatedly.

Example

  1. julia> Time("12:34pm", "HH:MMp")
  2. 12:34:00
  3. julia> a = ("12:34pm", "2:34am");
  4. julia> [Time(d, dateformat"HH:MMp") for d a] # preferred
  5. 2-element Vector{Time}:
  6. 12:34:00
  7. 02:34:00

source

Dates.Time — Method

  1. Time(t::AbstractString, df::DateFormat=ISOTimeFormat) -> Time

Construct a Time by parsing the t date time string following the pattern given in the DateFormat object, or dateformat”HH:MM:SS.s” if omitted.

Similar to Time(::AbstractString, ::AbstractString) but more efficient when repeatedly parsing similarly formatted time strings with a pre-created DateFormat object.

source

Dates.now — Method

  1. now() -> DateTime

Return a DateTime corresponding to the user’s system time including the system timezone locale.

source

Dates.now — Method

  1. now(::Type{UTC}) -> DateTime

Return a DateTime corresponding to the user’s system time as UTC/GMT.

source

Base.eps — Method

  1. eps(::Type{DateTime}) -> Millisecond
  2. eps(::Type{Date}) -> Day
  3. eps(::Type{Time}) -> Nanosecond
  4. eps(::TimeType) -> Period

Return the smallest unit value supported by the TimeType.

Examples

  1. julia> eps(DateTime)
  2. 1 millisecond
  3. julia> eps(Date)
  4. 1 day
  5. julia> eps(Time)
  6. 1 nanosecond

source

Accessor Functions

Dates.year — Function

  1. year(dt::TimeType) -> Int64

The year of a Date or DateTime as an Int64.

source

Dates.month — Function

  1. month(dt::TimeType) -> Int64

The month of a Date or DateTime as an Int64.

source

Dates.week — Function

  1. week(dt::TimeType) -> Int64

Return the ISO week date of a Date or DateTime as an Int64. 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 example, week(Date(2005, 1, 1)) is the 53rd week of 2004.

Examples

  1. julia> Dates.week(Date(1989, 6, 22))
  2. 25
  3. julia> Dates.week(Date(2005, 1, 1))
  4. 53
  5. julia> Dates.week(Date(2004, 12, 31))
  6. 53

source

Dates.day — Function

  1. day(dt::TimeType) -> Int64

The day of month of a Date or DateTime as an Int64.

source

Dates.hour — Function

  1. hour(dt::DateTime) -> Int64

The hour of day of a DateTime as an Int64.

source

  1. hour(t::Time) -> Int64

The hour of a Time as an Int64.

source

Dates.minute — Function

  1. minute(dt::DateTime) -> Int64

The minute of a DateTime as an Int64.

source

  1. minute(t::Time) -> Int64

The minute of a Time as an Int64.

source

Dates.second — Function

  1. second(dt::DateTime) -> Int64

The second of a DateTime as an Int64.

source

  1. second(t::Time) -> Int64

The second of a Time as an Int64.

source

Dates.millisecond — Function

  1. millisecond(dt::DateTime) -> Int64

The millisecond of a DateTime as an Int64.

source

  1. millisecond(t::Time) -> Int64

The millisecond of a Time as an Int64.

source

Dates.microsecond — Function

  1. microsecond(t::Time) -> Int64

The microsecond of a Time as an Int64.

source

Dates.nanosecond — Function

  1. nanosecond(t::Time) -> Int64

The nanosecond of a Time as an Int64.

source

Dates.Year — Method

  1. Year(v)

Construct a Year object with the given v value. Input must be losslessly convertible to an Int64.

source

Dates.Month — Method

  1. Month(v)

Construct a Month object with the given v value. Input must be losslessly convertible to an Int64.

source

Dates.Week — Method

  1. Week(v)

Construct a Week object with the given v value. Input must be losslessly convertible to an Int64.

source

Dates.Day — Method

  1. Day(v)

Construct a Day object with the given v value. Input must be losslessly convertible to an Int64.

source

Dates.Hour — Method

  1. Hour(dt::DateTime) -> Hour

The hour part of a DateTime as a Hour.

source

Dates.Minute — Method

  1. Minute(dt::DateTime) -> Minute

The minute part of a DateTime as a Minute.

source

Dates.Second — Method

  1. Second(dt::DateTime) -> Second

The second part of a DateTime as a Second.

source

Dates.Millisecond — Method

  1. Millisecond(dt::DateTime) -> Millisecond

The millisecond part of a DateTime as a Millisecond.

source

Dates.Microsecond — Method

  1. Microsecond(dt::Time) -> Microsecond

The microsecond part of a Time as a Microsecond.

source

Dates.Nanosecond — Method

  1. Nanosecond(dt::Time) -> Nanosecond

The nanosecond part of a Time as a Nanosecond.

source

Dates.yearmonth — Function

  1. yearmonth(dt::TimeType) -> (Int64, Int64)

Simultaneously return the year and month parts of a Date or DateTime.

source

Dates.monthday — Function

  1. monthday(dt::TimeType) -> (Int64, Int64)

Simultaneously return the month and day parts of a Date or DateTime.

source

Dates.yearmonthday — Function

  1. yearmonthday(dt::TimeType) -> (Int64, Int64, Int64)

Simultaneously return the year, month and day parts of a Date or DateTime.

source

Query Functions

Dates.dayname — Function

  1. dayname(dt::TimeType; locale="english") -> String
  2. dayname(day::Integer; locale="english") -> String

Return the full day name corresponding to the day of the week of the Date or DateTime in the given locale. Also accepts Integer.

Examples

  1. julia> Dates.dayname(Date("2000-01-01"))
  2. "Saturday"
  3. julia> Dates.dayname(4)
  4. "Thursday"

source

Dates.dayabbr — Function

  1. dayabbr(dt::TimeType; locale="english") -> String
  2. dayabbr(day::Integer; locale="english") -> String

Return the abbreviated name corresponding to the day of the week of the Date or DateTime in the given locale. Also accepts Integer.

Examples

  1. julia> Dates.dayabbr(Date("2000-01-01"))
  2. "Sat"
  3. julia> Dates.dayabbr(3)
  4. "Wed"

source

Dates.dayofweek — Function

  1. dayofweek(dt::TimeType) -> Int64

Return the day of the week as an Int64 with 1 = Monday, 2 = Tuesday, etc..

Examples

  1. julia> Dates.dayofweek(Date("2000-01-01"))
  2. 6

source

Dates.dayofmonth — Function

  1. dayofmonth(dt::TimeType) -> Int64

The day of month of a Date or DateTime as an Int64.

source

Dates.dayofweekofmonth — Function

  1. dayofweekofmonth(dt::TimeType) -> Int

For the day of week of dt, return which number it is in dt‘s month. So if the day of the week of dt is Monday, then 1 = First Monday of the month, 2 = Second Monday of the month, etc. In the range 1:5.

Examples

  1. julia> Dates.dayofweekofmonth(Date("2000-02-01"))
  2. 1
  3. julia> Dates.dayofweekofmonth(Date("2000-02-08"))
  4. 2
  5. julia> Dates.dayofweekofmonth(Date("2000-02-15"))
  6. 3

source

Dates.daysofweekinmonth — Function

  1. daysofweekinmonth(dt::TimeType) -> Int

For the day of week of dt, return the total number of that day of the week in dt‘s month. Returns 4 or 5. Useful in temporal expressions for specifying the last day of a week in a month by including dayofweekofmonth(dt) == daysofweekinmonth(dt) in the adjuster function.

Examples

  1. julia> Dates.daysofweekinmonth(Date("2005-01-01"))
  2. 5
  3. julia> Dates.daysofweekinmonth(Date("2005-01-04"))
  4. 4

source

Dates.monthname — Function

  1. monthname(dt::TimeType; locale="english") -> String
  2. monthname(month::Integer, locale="english") -> String

Return the full name of the month of the Date or DateTime or Integer in the given locale.

Examples

  1. julia> Dates.monthname(Date("2005-01-04"))
  2. "January"
  3. julia> Dates.monthname(2)
  4. "February"

source

Dates.monthabbr — Function

  1. monthabbr(dt::TimeType; locale="english") -> String
  2. monthabbr(month::Integer, locale="english") -> String

Return the abbreviated month name of the Date or DateTime or Integer in the given locale.

Examples

  1. julia> Dates.monthabbr(Date("2005-01-04"))
  2. "Jan"
  3. julia> monthabbr(2)
  4. "Feb"

source

Dates.daysinmonth — Function

  1. daysinmonth(dt::TimeType) -> Int

Return the number of days in the month of dt. Value will be 28, 29, 30, or 31.

Examples

  1. julia> Dates.daysinmonth(Date("2000-01"))
  2. 31
  3. julia> Dates.daysinmonth(Date("2001-02"))
  4. 28
  5. julia> Dates.daysinmonth(Date("2000-02"))
  6. 29

source

Dates.isleapyear — Function

  1. isleapyear(dt::TimeType) -> Bool

Return true if the year of dt is a leap year.

Examples

  1. julia> Dates.isleapyear(Date("2004"))
  2. true
  3. julia> Dates.isleapyear(Date("2005"))
  4. false

source

Dates.dayofyear — Function

  1. dayofyear(dt::TimeType) -> Int

Return the day of the year for dt with January 1st being day 1.

source

Dates.daysinyear — Function

  1. daysinyear(dt::TimeType) -> Int

Return 366 if the year of dt is a leap year, otherwise return 365.

Examples

  1. julia> Dates.daysinyear(1999)
  2. 365
  3. julia> Dates.daysinyear(2000)
  4. 366

source

Dates.quarterofyear — Function

  1. quarterofyear(dt::TimeType) -> Int

Return the quarter that dt resides in. Range of value is 1:4.

source

Dates.dayofquarter — Function

  1. dayofquarter(dt::TimeType) -> Int

Return the day of the current quarter of dt. Range of value is 1:92.

source

Adjuster Functions

Base.trunc — Method

  1. trunc(dt::TimeType, ::Type{Period}) -> TimeType

Truncates the value of dt according to the provided Period type.

Examples

  1. julia> trunc(Dates.DateTime("1996-01-01T12:30:00"), Dates.Day)
  2. 1996-01-01T00:00:00

source

Dates.firstdayofweek — Function

  1. firstdayofweek(dt::TimeType) -> TimeType

Adjusts dt to the Monday of its week.

Examples

  1. julia> Dates.firstdayofweek(DateTime("1996-01-05T12:30:00"))
  2. 1996-01-01T00:00:00

source

Dates.lastdayofweek — Function

  1. lastdayofweek(dt::TimeType) -> TimeType

Adjusts dt to the Sunday of its week.

Examples

  1. julia> Dates.lastdayofweek(DateTime("1996-01-05T12:30:00"))
  2. 1996-01-07T00:00:00

source

Dates.firstdayofmonth — Function

  1. firstdayofmonth(dt::TimeType) -> TimeType

Adjusts dt to the first day of its month.

Examples

  1. julia> Dates.firstdayofmonth(DateTime("1996-05-20"))
  2. 1996-05-01T00:00:00

source

Dates.lastdayofmonth — Function

  1. lastdayofmonth(dt::TimeType) -> TimeType

Adjusts dt to the last day of its month.

Examples

  1. julia> Dates.lastdayofmonth(DateTime("1996-05-20"))
  2. 1996-05-31T00:00:00

source

Dates.firstdayofyear — Function

  1. firstdayofyear(dt::TimeType) -> TimeType

Adjusts dt to the first day of its year.

Examples

  1. julia> Dates.firstdayofyear(DateTime("1996-05-20"))
  2. 1996-01-01T00:00:00

source

Dates.lastdayofyear — Function

  1. lastdayofyear(dt::TimeType) -> TimeType

Adjusts dt to the last day of its year.

Examples

  1. julia> Dates.lastdayofyear(DateTime("1996-05-20"))
  2. 1996-12-31T00:00:00

source

Dates.firstdayofquarter — Function

  1. firstdayofquarter(dt::TimeType) -> TimeType

Adjusts dt to the first day of its quarter.

Examples

  1. julia> Dates.firstdayofquarter(DateTime("1996-05-20"))
  2. 1996-04-01T00:00:00
  3. julia> Dates.firstdayofquarter(DateTime("1996-08-20"))
  4. 1996-07-01T00:00:00

source

Dates.lastdayofquarter — Function

  1. lastdayofquarter(dt::TimeType) -> TimeType

Adjusts dt to the last day of its quarter.

Examples

  1. julia> Dates.lastdayofquarter(DateTime("1996-05-20"))
  2. 1996-06-30T00:00:00
  3. julia> Dates.lastdayofquarter(DateTime("1996-08-20"))
  4. 1996-09-30T00:00:00

source

Dates.tonext — Method

  1. tonext(dt::TimeType, dow::Int; same::Bool=false) -> TimeType

Adjusts dt to the next day of week corresponding to dow with 1 = Monday, 2 = Tuesday, etc. Setting same=true allows the current dt to be considered as the next dow, allowing for no adjustment to occur.

source

Dates.toprev — Method

  1. toprev(dt::TimeType, dow::Int; same::Bool=false) -> TimeType

Adjusts dt to the previous day of week corresponding to dow with 1 = Monday, 2 = Tuesday, etc. Setting same=true allows the current dt to be considered as the previous dow, allowing for no adjustment to occur.

source

Dates.tofirst — Function

  1. tofirst(dt::TimeType, dow::Int; of=Month) -> TimeType

Adjusts dt to the first dow of its month. Alternatively, of=Year will adjust to the first dow of the year.

source

Dates.tolast — Function

  1. tolast(dt::TimeType, dow::Int; of=Month) -> TimeType

Adjusts dt to the last dow of its month. Alternatively, of=Year will adjust to the last dow of the year.

source

Dates.tonext — Method

  1. tonext(func::Function, dt::TimeType; step=Day(1), limit=10000, same=false) -> TimeType

Adjusts dt by iterating at most limit iterations by step increments until func returns true. func must take a single TimeType argument and return a Bool. same allows dt to be considered in satisfying func.

source

Dates.toprev — Method

  1. toprev(func::Function, dt::TimeType; step=Day(-1), limit=10000, same=false) -> TimeType

Adjusts dt by iterating at most limit iterations by step increments until func returns true. func must take a single TimeType argument and return a Bool. same allows dt to be considered in satisfying func.

source

Periods

Dates.Period — Method

  1. Year(v)
  2. Quarter(v)
  3. Month(v)
  4. Week(v)
  5. Day(v)
  6. Hour(v)
  7. Minute(v)
  8. Second(v)
  9. Millisecond(v)
  10. Microsecond(v)
  11. Nanosecond(v)

Construct a Period type with the given v value. Input must be losslessly convertible to an Int64.

source

Dates.CompoundPeriod — Method

  1. CompoundPeriod(periods) -> CompoundPeriod

Construct a CompoundPeriod from a Vector of Periods. All Periods of the same type will be added together.

Examples

  1. julia> Dates.CompoundPeriod(Dates.Hour(12), Dates.Hour(13))
  2. 25 hours
  3. julia> Dates.CompoundPeriod(Dates.Hour(-1), Dates.Minute(1))
  4. -1 hour, 1 minute
  5. julia> Dates.CompoundPeriod(Dates.Month(1), Dates.Week(-2))
  6. 1 month, -2 weeks
  7. julia> Dates.CompoundPeriod(Dates.Minute(50000))
  8. 50000 minutes

source

Dates.value — Function

  1. Dates.value(x::Period) -> Int64

For a given period, return the value associated with that period. For example, value(Millisecond(10)) returns 10 as an integer.

source

Dates.default — Function

  1. default(p::Period) -> Period

Returns a sensible “default” value for the input Period by returning T(1) for Year, Month, and Day, and T(0) for Hour, Minute, Second, and Millisecond.

source

Dates.periods — Function

  1. Dates.periods(::CompoundPeriod) -> Vector{Period}

Return the Vector of Periods that comprise the given CompoundPeriod.

Julia 1.7

This function requires Julia 1.7 or later.

source

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.

Base.floor — Method

  1. floor(dt::TimeType, p::Period) -> TimeType

Return the nearest Date or DateTime less than or equal to dt at resolution p.

For convenience, p may be a type instead of a value: floor(dt, Dates.Hour) is a shortcut for floor(dt, Dates.Hour(1)).

  1. julia> floor(Date(1985, 8, 16), Dates.Month)
  2. 1985-08-01
  3. julia> floor(DateTime(2013, 2, 13, 0, 31, 20), Dates.Minute(15))
  4. 2013-02-13T00:30:00
  5. julia> floor(DateTime(2016, 8, 6, 12, 0, 0), Dates.Day)
  6. 2016-08-06T00:00:00

source

Base.ceil — Method

  1. ceil(dt::TimeType, p::Period) -> TimeType

Return the nearest Date or DateTime greater than or equal to dt at resolution p.

For convenience, p may be a type instead of a value: ceil(dt, Dates.Hour) is a shortcut for ceil(dt, Dates.Hour(1)).

  1. julia> ceil(Date(1985, 8, 16), Dates.Month)
  2. 1985-09-01
  3. julia> ceil(DateTime(2013, 2, 13, 0, 31, 20), Dates.Minute(15))
  4. 2013-02-13T00:45:00
  5. julia> ceil(DateTime(2016, 8, 6, 12, 0, 0), Dates.Day)
  6. 2016-08-07T00:00:00

source

Base.round — Method

  1. round(dt::TimeType, p::Period, [r::RoundingMode]) -> TimeType

Return the Date or DateTime nearest to dt at resolution p. By default (RoundNearestTiesUp), ties (e.g., rounding 9:30 to the nearest hour) will be rounded up.

For convenience, p may be a type instead of a value: round(dt, Dates.Hour) is a shortcut for round(dt, Dates.Hour(1)).

  1. julia> round(Date(1985, 8, 16), Dates.Month)
  2. 1985-08-01
  3. julia> round(DateTime(2013, 2, 13, 0, 31, 20), Dates.Minute(15))
  4. 2013-02-13T00:30:00
  5. julia> round(DateTime(2016, 8, 6, 12, 0, 0), Dates.Day)
  6. 2016-08-07T00:00:00

Valid rounding modes for round(::TimeType, ::Period, ::RoundingMode) are RoundNearestTiesUp (default), RoundDown (floor), and RoundUp (ceil).

source

Most Period values can also be rounded to a specified resolution:

Base.floor — Method

  1. floor(x::Period, precision::T) where T <: Union{TimePeriod, Week, Day} -> T

Round x down to the nearest multiple of precision. If x and precision are different subtypes of Period, the return value will have the same type as precision.

For convenience, precision may be a type instead of a value: floor(x, Dates.Hour) is a shortcut for floor(x, Dates.Hour(1)).

  1. julia> floor(Dates.Day(16), Dates.Week)
  2. 2 weeks
  3. julia> floor(Dates.Minute(44), Dates.Minute(15))
  4. 30 minutes
  5. julia> floor(Dates.Hour(36), Dates.Day)
  6. 1 day

Rounding to a precision of Months or Years is not supported, as these Periods are of inconsistent length.

source

Base.ceil — Method

  1. ceil(x::Period, precision::T) where T <: Union{TimePeriod, Week, Day} -> T

Round x up to the nearest multiple of precision. If x and precision are different subtypes of Period, the return value will have the same type as precision.

For convenience, precision may be a type instead of a value: ceil(x, Dates.Hour) is a shortcut for ceil(x, Dates.Hour(1)).

  1. julia> ceil(Dates.Day(16), Dates.Week)
  2. 3 weeks
  3. julia> ceil(Dates.Minute(44), Dates.Minute(15))
  4. 45 minutes
  5. julia> ceil(Dates.Hour(36), Dates.Day)
  6. 2 days

Rounding to a precision of Months or Years is not supported, as these Periods are of inconsistent length.

source

Base.round — Method

  1. round(x::Period, precision::T, [r::RoundingMode]) where T <: Union{TimePeriod, Week, Day} -> T

Round x to the nearest multiple of precision. If x and precision are different subtypes of Period, the return value will have the same type as precision. By default (RoundNearestTiesUp), ties (e.g., rounding 90 minutes to the nearest hour) will be rounded up.

For convenience, precision may be a type instead of a value: round(x, Dates.Hour) is a shortcut for round(x, Dates.Hour(1)).

  1. julia> round(Dates.Day(16), Dates.Week)
  2. 2 weeks
  3. julia> round(Dates.Minute(44), Dates.Minute(15))
  4. 45 minutes
  5. julia> round(Dates.Hour(36), Dates.Day)
  6. 2 days

Valid rounding modes for round(::Period, ::T, ::RoundingMode) are RoundNearestTiesUp (default), RoundDown (floor), and RoundUp (ceil).

Rounding to a precision of Months or Years is not supported, as these Periods are of inconsistent length.

source

The following functions are not exported:

Dates.floorceil — Function

  1. floorceil(dt::TimeType, p::Period) -> (TimeType, TimeType)

Simultaneously return the floor and ceil of a Date or DateTime at resolution p. More efficient than calling both floor and ceil individually.

source

  1. floorceil(x::Period, precision::T) where T <: Union{TimePeriod, Week, Day} -> (T, T)

Simultaneously return the floor and ceil of Period at resolution p. More efficient than calling both floor and ceil individually.

source

Dates.epochdays2date — Function

  1. epochdays2date(days) -> Date

Take the number of days since the rounding epoch (0000-01-01T00:00:00) and return the corresponding Date.

source

Dates.epochms2datetime — Function

  1. epochms2datetime(milliseconds) -> DateTime

Take the number of milliseconds since the rounding epoch (0000-01-01T00:00:00) and return the corresponding DateTime.

source

Dates.date2epochdays — Function

  1. date2epochdays(dt::Date) -> Int64

Take the given Date and return the number of days since the rounding epoch (0000-01-01T00:00:00) as an Int64.

source

Dates.datetime2epochms — Function

  1. datetime2epochms(dt::DateTime) -> Int64

Take the given DateTime and return the number of milliseconds since the rounding epoch (0000-01-01T00:00:00) as an Int64.

source

Conversion Functions

Dates.today — Function

  1. today() -> Date

Return the date portion of now().

source

Dates.unix2datetime — Function

  1. unix2datetime(x) -> DateTime

Take the number of seconds since unix epoch 1970-01-01T00:00:00 and convert to the corresponding DateTime.

source

Dates.datetime2unix — Function

  1. datetime2unix(dt::DateTime) -> Float64

Take the given DateTime and return the number of seconds since the unix epoch 1970-01-01T00:00:00 as a Float64.

source

Dates.julian2datetime — Function

  1. julian2datetime(julian_days) -> DateTime

Take the number of Julian calendar days since epoch -4713-11-24T12:00:00 and return the corresponding DateTime.

source

Dates.datetime2julian — Function

  1. datetime2julian(dt::DateTime) -> Float64

Take the given DateTime and return the number of Julian calendar days since the julian epoch -4713-11-24T12:00:00 as a Float64.

source

Dates.rata2datetime — Function

  1. rata2datetime(days) -> DateTime

Take the number of Rata Die days since epoch 0000-12-31T00:00:00 and return the corresponding DateTime.

source

Dates.datetime2rata — Function

  1. datetime2rata(dt::TimeType) -> Int64

Return the number of Rata Die days since epoch from the given Date or DateTime.

source

Constants

Days of the Week:

VariableAbbr.Value (Int)
MondayMon1
TuesdayTue2
WednesdayWed3
ThursdayThu4
FridayFri5
SaturdaySat6
SundaySun7

Months of the Year:

VariableAbbr.Value (Int)
JanuaryJan1
FebruaryFeb2
MarchMar3
AprilApr4
MayMay5
JuneJun6
JulyJul7
AugustAug8
SeptemberSep9
OctoberOct10
NovemberNov11
DecemberDec12

Common Date Formatters

Dates.ISODateTimeFormat — Constant

  1. Dates.ISODateTimeFormat

Describes the ISO8601 formatting for a date and time. This is the default value for Dates.format of a DateTime.

Example

  1. julia> Dates.format(DateTime(2018, 8, 8, 12, 0, 43, 1), ISODateTimeFormat)
  2. "2018-08-08T12:00:43.001"

source

Dates.ISODateFormat — Constant

  1. Dates.ISODateFormat

Describes the ISO8601 formatting for a date. This is the default value for Dates.format of a Date.

Example

  1. julia> Dates.format(Date(2018, 8, 8), ISODateFormat)
  2. "2018-08-08"

source

Dates.ISOTimeFormat — Constant

  1. Dates.ISOTimeFormat

Describes the ISO8601 formatting for a time. This is the default value for Dates.format of a Time.

Example

  1. julia> Dates.format(Time(12, 0, 43, 1), ISOTimeFormat)
  2. "12:00:43.001"

source

Dates.RFC1123Format — Constant

  1. Dates.RFC1123Format

Describes the RFC1123 formatting for a date and time.

Example

  1. julia> Dates.format(DateTime(2018, 8, 8, 12, 0, 43, 1), RFC1123Format)
  2. "Wed, 08 Aug 2018 12:00:43"

source

  • 1The notion of the UT second is actually quite fundamental. There are basically two different notions of time generally accepted, one based on the physical rotation of the earth (one full rotation = 1 day), the other based on the SI second (a fixed, constant value). These are radically different! Think about it, a “UT second”, as defined relative to the rotation of the earth, may have a different absolute length depending on the day! Anyway, the fact that Date and DateTime are based on UT seconds is a simplifying, yet honest assumption so that things like leap seconds and all their complexity can be avoided. This basis of time is formally called UT or UT1. Basing types on the UT second basically means that every minute has 60 seconds and every day has 24 hours and leads to more natural calculations when working with calendar dates.