The times module contains routines and types for dealing with time using the proleptic Gregorian calendar. It's also available for the JavaScript target.
Although the times module supports nanosecond time resolution, the resolution used by getTime() depends on the platform and backend (JS is limited to millisecond precision).
import std/[times, os] # Simple benchmarking let time = cpuTime() sleep(100) # Replace this with something to be timed echo "Time taken: ", cpuTime() - time # Current date & time let now1 = now() # Current timestamp as a DateTime in local time let now2 = now().utc # Current timestamp as a DateTime in UTC let now3 = getTime() # Current timestamp as a Time # Arithmetic using Duration echo "One hour from now : ", now() + initDuration(hours = 1) # Arithmetic using TimeInterval echo "One year from now : ", now() + 1.years echo "One month from now : ", now() + 1.months
The DateTime type can be parsed and formatted using the different parse and format procedures.
let dt = parse("2000-01-01", "yyyy-MM-dd")
echo dt.format("yyyy-MM-dd") The different format patterns that are supported are documented below.
| Pattern | Description | Example |
|---|---|---|
d |
Numeric value representing the day of the month, it will be either one or two digits long. |
|
dd |
Same as above, but is always two digits. |
|
ddd |
Three letter string which indicates the day of the week. |
|
dddd |
Full string for the day of the week. |
|
GG |
The last two digits of the Iso Week-Year |
|
GGGG |
The Iso week-calendar year padded to four digits |
|
h |
The hours in one digit if possible. Ranging from 1-12. |
|
hh |
The hours in two digits always. If the hour is one digit, 0 is prepended. |
|
H |
The hours in one digit if possible, ranging from 0-23. |
|
HH |
The hours in two digits always. 0 is prepended if the hour is one digit. |
|
m |
The minutes in one digit if possible. |
|
mm |
Same as above but always two digits, 0 is prepended if the minute is one digit. |
|
M |
The month in one digit if possible. |
|
MM |
The month in two digits always. 0 is prepended if the month value is one digit. |
|
MMM |
Abbreviated three-letter form of the month. |
|
MMMM |
Full month string, properly capitalized. |
|
s |
Seconds as one digit if possible. |
|
ss |
Same as above but always two digits. 0 is prepended if the second is one digit. |
|
t |
A when time is in the AM. P when time is in the PM. |
|
tt |
Same as above, but AM and PM instead of A and P respectively. |
|
yy |
The last two digits of the year. When parsing, the current century is assumed. |
|
yyyy |
The year, padded to at least four digits. Is always positive, even when the year is BC. When the year is more than four digits, '+' is prepended. |
|
YYYY |
The year without any padding. Is always positive, even when the year is BC. |
|
uuuu |
The year, padded to at least four digits. Will be negative when the year is BC. When the year is more than four digits, '+' is prepended unless the year is BC. |
|
UUUU |
The year without any padding. Will be negative when the year is BC. |
|
V |
The Iso Week-Number as one or two digits |
|
VV |
The Iso Week-Number as two digits always. 0 is prepended if one digit. |
|
z |
Displays the timezone offset from UTC. |
|
zz |
Same as above but with leading 0. |
|
zzz |
Same as above but with :mm where mm represents minutes. |
|
ZZZ |
Same as above but with mm where mm represents minutes. |
|
zzzz |
Same as above but with :ss where ss represents seconds. |
|
ZZZZ |
Same as above but with ss where ss represents seconds. |
|
g |
Era: AD or BC |
|
fff |
Milliseconds display |
|
ffffff |
Microseconds display |
|
fffffffff |
Nanoseconds display |
|
Other strings can be inserted by putting them in ''. For example hh'->'mm will give 01->56. In addition to spaces, the following characters can be inserted without quoting them: : - , . ( ) / [ ]. A literal ' can be specified with ''.
However you don't need to necessarily separate format patterns, as an unambiguous format string like yyyyMMddhhmmss is also valid (although only for years in the range 1..9999).
The times module exports two similar types that are both used to represent some amount of time: Duration and TimeInterval. This section explains how they differ and when one should be preferred over the other (short answer: use Duration unless support for months and years is needed).
A Duration represents a duration of time stored as seconds and nanoseconds. A Duration is always fully normalized, so initDuration(hours = 1) and initDuration(minutes = 60) are equivalent.
Arithmetic with a Duration is very fast, especially when used with the Time type, since it only involves basic arithmetic. Because Duration is more performant and easier to understand it should generally preferred.
A TimeInterval represents an amount of time expressed in calendar units, for example "1 year and 2 days". Since some units cannot be normalized (the length of a year is different for leap years for example), the TimeInterval type uses separate fields for every unit. The TimeInterval's returned from this module generally don't normalize anything, so even units that could be normalized (like seconds, milliseconds and so on) are left untouched.
Arithmetic with a TimeInterval can be very slow, because it requires timezone information.
Since it's slower and more complex, the TimeInterval type should be avoided unless the program explicitly needs the features it offers that Duration doesn't have.
It should be especially noted that the handling of days differs between TimeInterval and Duration. The Duration type always treats a day as exactly 86400 seconds. For TimeInterval, it's more complex.
As an example, consider the amount of time between these two timestamps, both in the same timezone:
If only the date & time is considered, it appears that exactly one day has passed. However, the UTC offsets are different, which means that the UTC offset was changed somewhere in between. This happens twice each year for timezones that use daylight savings time. Because of this change, the amount of time that has passed is actually 25 hours.
The TimeInterval type uses calendar units, and will say that exactly one day has passed. The Duration type on the other hand normalizes everything to seconds, and will therefore say that 90000 seconds has passed, which is the same as 25 hours.
DateTime = object of RootObj
DateTime's returned by procedures in this module will never have a leap second. Source Edit DateTimeLocale = object MMM*: array[mJan .. mDec, string] MMMM*: array[mJan .. mDec, string] ddd*: array[dMon .. dSun, string] dddd*: array[dMon .. dSun, string]
Duration = object
Represents a fixed duration of time, meaning a duration that has constant length independent of the context.
To create a new Duration, use initDuration. Instead of trying to access the private attributes, use inSeconds for converting to seconds and inNanoseconds for converting to nanoseconds.
FixedTimeUnit = range[Nanoseconds .. Weeks]
TimeUnit that only includes units of fixed duration. These are the units that can be represented by a Duration. Source Edit IsoYear = distinct int
Month = enum mJan = (1, "January"), mFeb = "February", mMar = "March", mApr = "April", mMay = "May", mJun = "June", mJul = "July", mAug = "August", mSep = "September", mOct = "October", mNov = "November", mDec = "December"
1, so ord(month) will give the month number in the range 1..12. Source Edit SecondRange = range[0 .. 60]
second of a DateTime will never be a leap second. Source Edit TimeFormat = object ## \ ## Contains the patterns encoded as bytes. ## Literal values are encoded in a special way. ## They start with `Lit.byte`, then the length of the literal, then the ## raw char values of the literal. For example, the literal `foo` would ## be encoded as `@[Lit.byte, 3.byte, 'f'.byte, 'o'.byte, 'o'.byte]`.
Represents a format for parsing and printing time types.
To create a new TimeFormat use initTimeFormat proc.
TimeFormatParseError = object of ValueError
TimeFormat string fails. Source Edit TimeInterval = object nanoseconds*: int ## The number of nanoseconds microseconds*: int ## The number of microseconds milliseconds*: int ## The number of milliseconds seconds*: int ## The number of seconds minutes*: int ## The number of minutes hours*: int ## The number of hours days*: int ## The number of days weeks*: int ## The number of weeks months*: int ## The number of months years*: int ## The number of years
Represents a non-fixed duration of time. Can be used to add and subtract non-fixed time units from a DateTime or Time.
Create a new TimeInterval with initTimeInterval proc.
Note that TimeInterval doesn't represent a fixed duration of time, since the duration of some units depend on the context (e.g a year can be either 365 or 366 days long). The non-fixed time units are years, months, days and week.
Note that TimeInterval's returned from the times module are never normalized. If you want to normalize a time unit, Duration should be used instead.
TimeParseError = object of ValueError
TimeFormat fails. Source Edit TimeUnit = enum Nanoseconds, Microseconds, Milliseconds, Seconds, Minutes, Hours, Days, Weeks, Months, Years
Timezone = ref object
times module only supplies implementations for the system's local time and UTC. Source Edit WeekDay = enum dMon = "Monday", dTue = "Tuesday", dWed = "Wednesday", dThu = "Thursday", dFri = "Friday", dSat = "Saturday", dSun = "Sunday"
ZonedTime = object
time*: Time ## The point in time being represented.
utcOffset*: int ## The offset in seconds west of UTC,
## including any offset due to DST.
isDst*: bool ## Determines whether DST is in effect.DefaultLocale = (MMM: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug",
"Sep", "Oct", "Nov", "Dec"], MMMM: ["January",
"February", "March", "April", "May", "June", "July", "August", "September",
"October", "November", "December"],
ddd: ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"], dddd: [
"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"])proc `$`(dt: DateTime): string {....tags: [], raises: [], gcsafe, forbids: [].}DateTime object to a string representation. It uses the format yyyy-MM-dd'T'HH:mm:sszzz. Example:
let dt = dateTime(2000, mJan, 01, 12, 00, 00, 00, utc()) doAssert $dt == "2000-01-01T12:00:00Z" doAssert $default(DateTime) == "Uninitialized DateTime"Source Edit
proc `$`(dur: Duration): string {....raises: [], tags: [], forbids: [].}Duration. Example:
doAssert $initDuration(seconds = 2) == "2 seconds" doAssert $initDuration(weeks = 1, days = 2) == "1 week and 2 days" doAssert $initDuration(hours = 1, minutes = 2, seconds = 3) == "1 hour, 2 minutes, and 3 seconds" doAssert $initDuration(milliseconds = -1500) == "-1 second and -500 milliseconds"Source Edit
proc `$`(f: TimeFormat): string {....raises: [], tags: [], forbids: [].}f. Example:
let f = initTimeFormat("yyyy-MM-dd")
doAssert $f == "yyyy-MM-dd" Source Edit proc `$`(ti: TimeInterval): string {....raises: [], tags: [], forbids: [].}TimeInterval. Example:
doAssert $initTimeInterval(years = 1, nanoseconds = 123) == "1 year and 123 nanoseconds" doAssert $initTimeInterval() == "0 nanoseconds"Source Edit
proc `$`(time: Time): string {....tags: [], raises: [], gcsafe, forbids: [].}Time value to a string representation. It will use the local time zone and use the format yyyy-MM-dd'T'HH:mm:sszzz. Example:
let dt = dateTime(1970, mJan, 01, 00, 00, 00, 00, local()) let tm = dt.toTime() doAssert $tm == "1970-01-01T00:00:00" & format(dt, "zzz")Source Edit
proc `*`(a: Duration; b: int64): Duration {....gcsafe, noSideEffect, ...gcsafe,
extern: "ntMulDuration", raises: [], tags: [], forbids: [].}Example:
doAssert initDuration(seconds = 1) * 5 == initDuration(seconds = 5) doAssert initDuration(minutes = 45) * 3 == initDuration(hours = 2, minutes = 15)Source Edit
proc `*`(a: int64; b: Duration): Duration {....gcsafe, noSideEffect, ...gcsafe,
extern: "ntMulInt64Duration", raises: [], tags: [], forbids: [].}Example:
doAssert 5 * initDuration(seconds = 1) == initDuration(seconds = 5) doAssert 3 * initDuration(minutes = 45) == initDuration(hours = 2, minutes = 15)Source Edit
proc `+`(a, b: Duration): Duration {....gcsafe, noSideEffect, ...gcsafe,
extern: "ntAddDuration", raises: [],
tags: [], forbids: [].}Example:
doAssert initDuration(seconds = 1) + initDuration(days = 1) == initDuration(seconds = 1, days = 1)Source Edit
proc `+`(a: Time; b: Duration): Time {....gcsafe, noSideEffect, ...gcsafe,
extern: "ntAddTime", raises: [],
tags: [], forbids: [].}Time. Example:
doAssert (fromUnix(0) + initDuration(seconds = 1)) == fromUnix(1)Source Edit
proc `+`(dt: DateTime; dur: Duration): DateTime {....raises: [], tags: [],
forbids: [].}Example:
let dt = dateTime(2017, mMar, 30, 00, 00, 00, 00, utc()) let dur = initDuration(hours = 5) doAssert $(dt + dur) == "2017-03-30T05:00:00Z"Source Edit
proc `+`(dt: DateTime; interval: TimeInterval): DateTime {....raises: [], tags: [],
forbids: [].}Adds interval to dt. Components from interval are added in the order of their size, i.e. first the years component, then the months component and so on. The returned DateTime will have the same timezone as the input.
Note that when adding months, monthday overflow is allowed. This means that if the resulting month doesn't have enough days it, the month will be incremented and the monthday will be set to the number of days overflowed. So adding one month to 31 October will result in 31 November, which will overflow and result in 1 December.
Example:
let dt = dateTime(2017, mMar, 30, 00, 00, 00, 00, utc()) doAssert $(dt + 1.months) == "2017-04-30T00:00:00Z" # This is correct and happens due to monthday overflow. doAssert $(dt - 1.months) == "2017-03-02T00:00:00Z"Source Edit
proc `-`(a, b: Duration): Duration {....gcsafe, noSideEffect, ...gcsafe,
extern: "ntSubDuration", raises: [],
tags: [], forbids: [].}Example:
doAssert initDuration(seconds = 1, days = 1) - initDuration(seconds = 1) == initDuration(days = 1)Source Edit
proc `-`(a, b: Time): Duration {....gcsafe, noSideEffect, ...gcsafe,
extern: "ntDiffTime", raises: [], tags: [],
forbids: [].}Example:
doAssert initTime(1000, 100) - initTime(500, 20) == initDuration(minutes = 8, seconds = 20, nanoseconds = 80)Source Edit
proc `-`(a: Duration): Duration {....gcsafe, noSideEffect, ...gcsafe,
extern: "ntReverseDuration", raises: [],
tags: [], forbids: [].}Example:
doAssert -initDuration(seconds = 1) == initDuration(seconds = -1)Source Edit
proc `-`(a: Time; b: Duration): Time {....gcsafe, noSideEffect, ...gcsafe,
extern: "ntSubTime", raises: [],
tags: [], forbids: [].}Time. Example:
doAssert (fromUnix(0) - initDuration(seconds = 1)) == fromUnix(-1)Source Edit
proc `-`(dt1, dt2: DateTime): Duration {....raises: [], tags: [], forbids: [].}dt1 and dt2. Example:
let dt1 = dateTime(2017, mMar, 30, 00, 00, 00, 00, utc()) let dt2 = dateTime(2017, mMar, 25, 00, 00, 00, 00, utc()) doAssert dt1 - dt2 == initDuration(days = 5)Source Edit
proc `-`(dt: DateTime; dur: Duration): DateTime {....raises: [], tags: [],
forbids: [].}Example:
let dt = dateTime(2017, mMar, 30, 00, 00, 00, 00, utc()) let dur = initDuration(days = 5) doAssert $(dt - dur) == "2017-03-25T00:00:00Z"Source Edit
proc `-`(dt: DateTime; interval: TimeInterval): DateTime {....raises: [], tags: [],
forbids: [].}interval from dt. Components from interval are subtracted in the order of their size, i.e. first the years component, then the months component and so on. The returned DateTime will have the same timezone as the input. Example:
let dt = dateTime(2017, mMar, 30, 00, 00, 00, 00, utc()) doAssert $(dt - 5.days) == "2017-03-25T00:00:00Z"Source Edit
proc `-`(ti1, ti2: TimeInterval): TimeInterval {....raises: [], tags: [],
forbids: [].}Subtracts TimeInterval ti1 from ti2.
Time components are subtracted one-by-one, see output:
Example:
let ti1 = initTimeInterval(hours = 24) let ti2 = initTimeInterval(hours = 4) doAssert (ti1 - ti2) == initTimeInterval(hours = 20)Source Edit
proc `-`(ti: TimeInterval): TimeInterval {....raises: [], tags: [], forbids: [].}Example:
let day = -initTimeInterval(hours = 24) doAssert day.hours == -24Source Edit
proc `-`(time: Time; interval: TimeInterval): Time {....raises: [], tags: [],
forbids: [].}interval from Time time. If interval contains any years, months, weeks or days the operation is performed in the local timezone. Example:
let tm = fromUnix(5) doAssert tm - 5.seconds == fromUnix(0)Source Edit
proc `<`(a, b: DateTime): bool {....raises: [], tags: [], forbids: [].}a happened before b. Source Edit proc `<`(a, b: Duration): bool {....gcsafe, noSideEffect, ...gcsafe,
extern: "ntLtDuration", raises: [], tags: [],
forbids: [].}a < b is true a might represent a larger absolute duration. Use abs(a) < abs(b) to compare the absolute duration. Example:
doAssert initDuration(seconds = 1) < initDuration(seconds = 2) doAssert initDuration(seconds = -2) < initDuration(seconds = 1) doAssert initDuration(seconds = -2).abs < initDuration(seconds = 1).abs == falseSource Edit
proc `<=`(a, b: DateTime): bool {....raises: [], tags: [], forbids: [].}a happened before or at the same time as b. Source Edit proc `==`(a, b: DateTime): bool {....raises: [], tags: [], forbids: [].}a and b represent the same point in time. Source Edit proc `==`(a, b: Duration): bool {....gcsafe, noSideEffect, ...gcsafe,
extern: "ntEqDuration", raises: [], tags: [],
forbids: [].}Example:
let d1 = initDuration(weeks = 1) d2 = initDuration(days = 7) doAssert d1 == d2Source Edit
proc between(startDt, endDt: DateTime): TimeInterval {....raises: [], tags: [],
forbids: [].}startDt and endDt as a TimeInterval. The following guarantees about the result is given:startDt.timezone == endDt.timezone, it is guaranteed that startDt + between(startDt, endDt) == endDt.startDt.timezone != endDt.timezone, then the result will be equivalent to between(startDt.utc, endDt.utc).Example:
var a = dateTime(2015, mMar, 25, 12, 0, 0, 00, utc()) var b = dateTime(2017, mApr, 1, 15, 0, 15, 00, utc()) var ti = initTimeInterval(years = 2, weeks = 1, hours = 3, seconds = 15) doAssert between(a, b) == ti doAssert between(a, b) == -between(b, a)Source Edit
proc convert[T: SomeInteger](unitFrom, unitTo: FixedTimeUnit; quantity: T): T {.
inline.}Example:
doAssert convert(Days, Hours, 2) == 48 doAssert convert(Days, Weeks, 13) == 1 # Truncated doAssert convert(Seconds, Milliseconds, -1) == -1000Source Edit
proc cpuTime(): float {....tags: [TimeEffect], raises: [], forbids: [].}epochTime. However, it may measure the real time instead (depending on the OS). The value of the result has no meaning. To generate useful timing values, take the difference between the results of two cpuTime calls: Example:
var t0 = cpuTime() # some useless work here (calculate fibonacci) var fib = @[0, 1, 1] for i in 1..10: fib.add(fib[^1] + fib[^2]) echo "CPU time [s] ", cpuTime() - t0 echo "Fib is [s] ", fibWhen the flag
--benchmarkVM is passed to the compiler, this proc is also available at compile time Source Edit proc dateTime(year: int; month: Month; monthday: MonthdayRange;
hour: HourRange = 0; minute: MinuteRange = 0;
second: SecondRange = 0; nanosecond: NanosecondRange = 0;
zone: Timezone = local()): DateTime {....raises: [], tags: [],
forbids: [].}Example:
assert $dateTime(2017, mMar, 30, zone = utc()) == "2017-03-30T00:00:00Z"Source Edit
proc `div`(a: Duration; b: int64): Duration {....gcsafe, noSideEffect, ...gcsafe,
extern: "ntDivDuration", raises: [], tags: [], forbids: [].}Example:
doAssert initDuration(seconds = 3) div 2 == initDuration(milliseconds = 1500) doAssert initDuration(minutes = 45) div 30 == initDuration(minutes = 1, seconds = 30) doAssert initDuration(nanoseconds = 3) div 2 == initDuration(nanoseconds = 1)Source Edit
proc epochTime(): float {....tags: [TimeEffect], raises: [], forbids: [].}Gets time after the UNIX epoch (1970) in seconds. It is a float because sub-second resolution is likely to be supported (depending on the hardware/OS).
getTime should generally be preferred over this proc.
now), use monotimes.getMonoTime or cpuTime instead, depending on the use case.proc format(dt: DateTime; f: static[string]): string {....raises: [].}format at compile time. Source Edit proc format(dt: DateTime; f: string; loc: DateTimeLocale = DefaultLocale): string {.
...raises: [TimeFormatParseError], tags: [], forbids: [].}Shorthand for constructing a TimeFormat and using it to format dt.
See Parsing and formatting dates for documentation of the format argument.
Example:
let dt = dateTime(2000, mJan, 01, 00, 00, 00, 00, utc()) doAssert "2000-01-01" == format(dt, "yyyy-MM-dd")Source Edit
proc format(dt: DateTime; f: TimeFormat; loc: DateTimeLocale = DefaultLocale): string {.
...raises: [], tags: [], forbids: [].}dt using the format specified by f. Example:
let f = initTimeFormat("yyyy-MM-dd")
let dt = dateTime(2000, mJan, 01, 00, 00, 00, 00, utc())
doAssert "2000-01-01" == dt.format(f) Source Edit proc format(time: Time; f: static[string]; zone: Timezone = local()): string {.
...raises: [].}f at compile time. Source Edit proc format(time: Time; f: string; zone: Timezone = local()): string {.
...raises: [TimeFormatParseError], tags: [], forbids: [].}Shorthand for constructing a TimeFormat and using it to format time. Will use the timezone specified by zone.
See Parsing and formatting dates for documentation of the f argument.
Example:
var dt = dateTime(1970, mJan, 01, 00, 00, 00, 00, utc()) var tm = dt.toTime() doAssert format(tm, "yyyy-MM-dd'T'HH:mm:ss", utc()) == "1970-01-01T00:00:00"Source Edit
proc fromUnixFloat(seconds: float): Time {....gcsafe, tags: [], raises: [],
noSideEffect, ...forbids: [].}Time; same as fromUnix but with subsecond resolution. Example:
doAssert fromUnixFloat(123456.0) == fromUnixFloat(123456) doAssert fromUnixFloat(-123456.0) == fromUnixFloat(-123456)Source Edit
proc getDayOfWeek(monthday: MonthdayRange; month: Month; year: int): WeekDay {.
...tags: [], raises: [], gcsafe, forbids: [].}dateTime(year, month, monthday, 0, 0, 0, 0).weekday. Example:
doAssert getDayOfWeek(13, mJun, 1990) == dWed doAssert $getDayOfWeek(13, mJun, 1990) == "Wednesday"Source Edit
proc getDayOfYear(monthday: MonthdayRange; month: Month; year: int): YeardayRange {.
...tags: [], raises: [], gcsafe, forbids: [].}dateTime(year, month, monthday, 0, 0, 0, 0).yearday. Example:
doAssert getDayOfYear(1, mJan, 2000) == 0 doAssert getDayOfYear(10, mJan, 2000) == 9 doAssert getDayOfYear(10, mFeb, 2000) == 40Source Edit
proc getIsoWeekAndYear(dt: DateTime): tuple[isoweek: IsoWeekRange,
isoyear: IsoYear] {....raises: [], tags: [], forbids: [].}Example:
assert getIsoWeekAndYear(initDateTime(21, mApr, 2018, 00, 00, 00)) == (isoweek: 16.IsoWeekRange, isoyear: 2018.IsoYear) block: let (w, y) = getIsoWeekAndYear(initDateTime(30, mDec, 2019, 00, 00, 00)) assert w == 01.IsoWeekRange assert y == 2020.IsoYear assert getIsoWeekAndYear(initDateTime(13, mSep, 2020, 00, 00, 00)) == (isoweek: 37.IsoWeekRange, isoyear: 2020.IsoYear) block: let (w, y) = getIsoWeekAndYear(initDateTime(2, mJan, 2021, 00, 00, 00)) assert w.int > 52 assert w.int < 54 assert y.int mod 100 == 20Source Edit
proc getWeeksInIsoYear(y: IsoYear): IsoWeekRange {....raises: [], tags: [],
forbids: [].}Example:
assert getWeeksInIsoYear(IsoYear(2019)) == 52 assert getWeeksInIsoYear(IsoYear(2020)) == 53Source Edit
proc initDateTime(monthday: MonthdayRange; month: Month; year: int;
hour: HourRange; minute: MinuteRange; second: SecondRange;
nanosecond: NanosecondRange; zone: Timezone = local()): DateTime {.
...deprecated: "use `dateTime`", raises: [], tags: [], forbids: [].}Example: cmd: --warning:deprecated:off
assert $initDateTime(30, mMar, 2017, 00, 00, 00, 00, utc()) == "2017-03-30T00:00:00Z"Source Edit
proc initDateTime(monthday: MonthdayRange; month: Month; year: int;
hour: HourRange; minute: MinuteRange; second: SecondRange;
zone: Timezone = local()): DateTime {.
...deprecated: "use `dateTime`", raises: [], tags: [], forbids: [].}Example: cmd: --warning:deprecated:off
assert $initDateTime(30, mMar, 2017, 00, 00, 00, utc()) == "2017-03-30T00:00:00Z"Source Edit
proc initDuration(nanoseconds, microseconds, milliseconds, seconds, minutes,
hours, days, weeks: int64 = 0): Duration {....raises: [],
tags: [], forbids: [].}Example:
let dur = initDuration(seconds = 1, milliseconds = 1) doAssert dur.inMilliseconds == 1001 doAssert dur.inSeconds == 1Source Edit
proc initTimeFormat(format: string): TimeFormat {.
...raises: [TimeFormatParseError], tags: [], forbids: [].}Construct a new time format for parsing & formatting time types.
See Parsing and formatting dates for documentation of the format argument.
Example:
let f = initTimeFormat("yyyy-MM-dd")
doAssert "2000-01-01" == "2000-01-01".parse(f).format(f) Source Edit proc initTimeInterval(nanoseconds, microseconds, milliseconds, seconds, minutes,
hours, days, weeks, months, years: int = 0): TimeInterval {.
...raises: [], tags: [], forbids: [].}Creates a new TimeInterval.
This proc doesn't perform any normalization! For example, initTimeInterval(hours = 24) and initTimeInterval(days = 1) are not equal.
You can also use the convenience procedures called milliseconds, seconds, minutes, hours, days, months, and years.
Example:
let day = initTimeInterval(hours = 24) let dt = dateTime(2000, mJan, 01, 12, 00, 00, 00, utc()) doAssert $(dt + day) == "2000-01-02T12:00:00Z" doAssert initTimeInterval(hours = 24) != initTimeInterval(days = 1)Source Edit
proc isLeapDay(dt: DateTime): bool {....raises: [], tags: [], forbids: [].}t is a leap day, i.e. Feb 29 in a leap year. This matters as it affects time offset calculations. Example:
let dt = dateTime(2020, mFeb, 29, 00, 00, 00, 00, utc()) doAssert dt.isLeapDay doAssert dt+1.years-1.years != dt let dt2 = dateTime(2020, mFeb, 28, 00, 00, 00, 00, utc()) doAssert not dt2.isLeapDay doAssert dt2+1.years-1.years == dt2 doAssertRaises(Exception): discard dateTime(2021, mFeb, 29, 00, 00, 00, 00, utc())Source Edit
proc local(): Timezone {....raises: [], tags: [], forbids: [].}Timezone implementation for the local timezone. Example:
doAssert now().timezone == local() doAssert local().name == "LOCAL"Source Edit
proc name(zone: Timezone): string {....raises: [], tags: [], forbids: [].}The name of the timezone.
If possible, the name will be the name used in the tz database. If the timezone doesn't exist in the tz database, or if the timezone name is unknown, then any string that describes the timezone unambiguously might be used. For example, the string "LOCAL" is used for the system's local timezone.
See also: https://en.wikipedia.org/wiki/Tz_database
Source Editproc newTimezone(name: string; zonedTimeFromTimeImpl: proc (time: Time): ZonedTime {.
...tags: [], raises: [], gcsafe.}; zonedTimeFromAdjTimeImpl: proc (
adjTime: Time): ZonedTime {....tags: [], raises: [], gcsafe.}): owned Timezone {.
...raises: [], tags: [], forbids: [].}Create a new Timezone.
zonedTimeFromTimeImpl and zonedTimeFromAdjTimeImpl is used as the underlying implementations for zonedTimeFromTime and zonedTimeFromAdjTime.
If possible, the name parameter should match the name used in the tz database. If the timezone doesn't exist in the tz database, or if the timezone name is unknown, then any string that describes the timezone unambiguously can be used. Note that the timezones name is used for checking equality!
Example:
proc utcTzInfo(time: Time): ZonedTime =
ZonedTime(utcOffset: 0, isDst: false, time: time)
let utc = newTimezone("Etc/UTC", utcTzInfo, utcTzInfo) Source Edit proc parse(input, f: string; tz: Timezone = local();
loc: DateTimeLocale = DefaultLocale): DateTime {.
...raises: [TimeParseError, TimeFormatParseError], tags: [TimeEffect],
forbids: [].}Shorthand for constructing a TimeFormat and using it to parse input as a DateTime.
See Parsing and formatting dates for documentation of the f argument.
Example:
let dt = dateTime(2000, mJan, 01, 00, 00, 00, 00, utc())
doAssert dt == parse("2000-01-01", "yyyy-MM-dd", utc()) Source Edit proc parse(input: string; f: static[string]; zone: Timezone = local();
loc: DateTimeLocale = DefaultLocale): DateTime {.
...raises: [TimeParseError].}f at compile time. Source Edit proc parse(input: string; f: TimeFormat; zone: Timezone = local();
loc: DateTimeLocale = DefaultLocale): DateTime {.
...raises: [TimeParseError], tags: [TimeEffect], forbids: [].}Parses input as a DateTime using the format specified by f. If no UTC offset was parsed, then input is assumed to be specified in the zone timezone. If a UTC offset was parsed, the result will be converted to the zone timezone.
Month and day names from the passed in loc are used.
Example:
let f = initTimeFormat("yyyy-MM-dd")
let dt = dateTime(2000, mJan, 01, 00, 00, 00, 00, utc())
doAssert dt == "2000-01-01".parse(f, utc()) Source Edit proc parseTime(input, f: string; zone: Timezone): Time {.
...raises: [TimeParseError, TimeFormatParseError], tags: [TimeEffect],
forbids: [].}Shorthand for constructing a TimeFormat and using it to parse input as a DateTime, then converting it a Time.
See Parsing and formatting dates for documentation of the format argument.
Example:
let tStr = "1970-01-01T00:00:00+00:00" doAssert parseTime(tStr, "yyyy-MM-dd'T'HH:mm:sszzz", utc()) == fromUnix(0)Source Edit
proc toParts(dur: Duration): DurationParts {....raises: [], tags: [], forbids: [].}Converts a duration into an array consisting of fixed time units.
Each value in the array gives information about a specific unit of time, for example result[Days] gives a count of days.
This procedure is useful for converting Duration values to strings.
Example:
var dp = toParts(initDuration(weeks = 2, days = 1)) doAssert dp[Days] == 1 doAssert dp[Weeks] == 2 doAssert dp[Minutes] == 0 dp = toParts(initDuration(days = -1)) doAssert dp[Days] == -1Source Edit
proc toParts(ti: TimeInterval): TimeIntervalParts {....raises: [], tags: [],
forbids: [].}Converts a TimeInterval into an array consisting of its time units, starting with nanoseconds and ending with years.
This procedure is useful for converting TimeInterval values to strings. E.g. then you need to implement custom interval printing
Example:
var tp = toParts(initTimeInterval(years = 1, nanoseconds = 123)) doAssert tp[Years] == 1 doAssert tp[Nanoseconds] == 123Source Edit
proc utc(): Timezone {....raises: [], tags: [], forbids: [].}Timezone implementation for the UTC timezone. Example:
doAssert now().utc.timezone == utc() doAssert utc().name == "Etc/UTC"Source Edit
proc utcOffset(dt: DateTime): int {.inline, ...raises: [], tags: [], forbids: [].}+01:00 (which would be equivalent to the UTC offset -3600). Source Edit proc zonedTimeFromAdjTime(zone: Timezone; adjTime: Time): ZonedTime {.
...raises: [], tags: [], forbids: [].}Returns the ZonedTime for some local time.
Note that the Time argument does not represent a point in time, it represent a local time! E.g if adjTime is fromUnix(0), it should be interpreted as 1970-01-01T00:00:00 in the zone timezone, not in UTC.
© 2006–2024 Andreas Rumpf
Licensed under the MIT License.
https://nim-lang.org/docs/times.html