This module contains routines and types for dealing with time. This module is available for the JavaScript target. The proleptic Gregorian calendar is the only calendar supported.
Examples:
import times, os let time = cpuTime() sleep(100) # replace this with something to be timed echo "Time taken: ",cpuTime() - time echo "My formatted time: ", format(now(), "d MMMM yyyy HH:mm") echo "Using predefined formats: ", getClockStr(), " ", getDateStr() echo "epochTime() float value: ", epochTime() echo "cpuTime() float value: ", cpuTime() echo "An hour from now : ", now() + 1.hours echo "An hour from (UTC) now: ", getTime().utc + initInterval(0,0,0,1)
Types
Month = enum mJan = 1, mFeb, mMar, mApr, mMay, mJun, mJul, mAug, mSep, mOct, mNov, mDec
- Represents a month. Note that the enum starts at 1, so ord(month) will give the month number in the range [1..12]. Source Edit
WeekDay = enum dMon, dTue, dWed, dThu, dFri, dSat, dSun
- Represents a weekday. Source Edit
MonthdayRange = range[1 .. 31]
- Source Edit
HourRange = range[0 .. 23]
- Source Edit
MinuteRange = range[0 .. 59]
- Source Edit
SecondRange = range[0 .. 60]
- Source Edit
YeardayRange = range[0 .. 365]
- Source Edit
Time = distinct TimeImpl
- Represents a point in time. This is currently implemented as a int64 representing seconds since 1970-01-01T00:00:00Z, but don't rely on this knowledge because it might change in the future to allow for higher precision. Use the procs toUnix and fromUnix to work with unix timestamps instead. Source Edit
DateTime = object of RootObj second*: SecondRange ## The number of seconds after the minute, ## normally in the range 0 to 59, but can ## be up to 60 to allow for a leap second. minute*: MinuteRange ## The number of minutes after the hour, ## in the range 0 to 59. hour*: HourRange ## The number of hours past midnight, ## in the range 0 to 23. monthday*: MonthdayRange ## The day of the month, in the range 1 to 31. month*: Month ## The current month. year*: int ## The current year, using astronomical year numbering ## (meaning that before year 1 is year 0, then year -1 and so on). weekday*: WeekDay ## The current day of the week. yearday*: YeardayRange ## The number of days since January 1, ## in the range 0 to 365. isDst*: bool ## Determines whether DST is in effect. ## Always false for the JavaScript backend. timezone*: Timezone ## The timezone represented as an implementation of ``Timezone``. utcOffset*: int ## The offset in seconds west of UTC, including any offset due to DST. ## Note that the sign of this number is the opposite ## of the one in a formatted offset string like ``+01:00`` ## (which would be parsed into the UTC offset ``-3600``).
- Represents a time in different parts. Although this type can represent leap seconds, they are generally not supported in this module. They are not ignored, but the DateTime's returned by procedures in this module will never have a leap second. Source Edit
TimeInterval = object 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 months*: int ## The number of months years*: int ## The number of years
- Represents a duration of time. Can be used to add and subtract from a DateTime or Time. Note that a 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 and days. Source Edit
Timezone = object zoneInfoFromUtc*: proc (time: Time): ZonedTime {.
tags: [], raises: [], gcsafe, locks: 0.} zoneInfoFromTz*: proc (adjTime: Time): ZonedTime {.tags: [], raises: [], gcsafe, locks: 0.} name*: string ## The name of the timezone, f.ex 'Europe/Stockholm' or 'Etc/UTC'. Used for checking equality. ## Se also: https://en.wikipedia.org/wiki/List_of_tz_database_time_zones- Timezone interface for supporting DateTime's of arbritary timezones. The times module only supplies implementations for the systems local time and UTC. The members zoneInfoFromUtc and zoneInfoFromTz should not be accessed directly and are only exported so that Timezone can be implemented by other modules. Source Edit
ZonedTime = object adjTime*: Time ## Time adjusted to a timezone. utcOffset*: int isDst*: bool
- Represents a zooned instant in time that is not associated with any calendar. This type is only used for implementing timezones. Source Edit
Procs
proc fromUnix(unix: int64): Time {.
gcsafe, locks: 0, tags: [], raises: [], noSideEffect.}- Convert a unix timestamp (seconds since 1970-01-01T00:00:00Z) to a Time. Source Edit
proc toUnix(t: Time): int64 {.
gcsafe, locks: 0, tags: [], raises: [], noSideEffect.}- Convert t to a unix timestamp (seconds since 1970-01-01T00:00:00Z). Source Edit
proc isLeapYear(year: int): bool {.
raises: [], tags: [].}- Returns true if year is a leap year. Source Edit
proc getDaysInMonth(month: Month; year: int): int {.
raises: [], tags: [].}- Get the number of days in a month of a year. Source Edit
proc getDaysInYear(year: int): int {.
raises: [], tags: [].}- Get the number of days in a year Source Edit
proc getDayOfYear(monthday: MonthdayRange; month: Month; year: int): YeardayRange {.
tags: [], raises: [], gcsafe, locks: 0.}- Returns the day of the year. Equivalent with initDateTime(day, month, year).yearday. Source Edit
proc getDayOfWeek(monthday: MonthdayRange; month: Month; year: int): WeekDay {.
tags: [], raises: [], gcsafe, locks: 0.}- Returns the day of the week enum from day, month and year. Equivalent with initDateTime(day, month, year).weekday. Source Edit
proc `-`(a, b: Time): int64 {.
gcsafe, extern: "ntDiffTime", tags: [], raises: [], noSideEffect, gcsafe, locks: 0, deprecated.}-
Computes the difference of two calendar times. Result is in seconds. This is deprecated because it will need to change when sub second time resolution is implemented. Use a.toUnix - b.toUnix instead.
let a = fromSeconds(1_000_000_000) let b = fromSeconds(1_500_000_000) echo initInterval(seconds=int(b - a)) # (milliseconds: 0, seconds: 20, minutes: 53, hours: 0, days: 5787, months: 0, years: 0)
Source Edit proc `<`(a, b: Time): bool {.
gcsafe, extern: "ntLtTime", tags: [], raises: [], noSideEffect, borrow.}- Returns true iff a < b, that is iff a happened before b. Source Edit
proc `<=`(a, b: Time): bool {.
gcsafe, extern: "ntLeTime", tags: [], raises: [], noSideEffect, borrow.}- Returns true iff a <= b. Source Edit
proc `==`(a, b: Time): bool {.
gcsafe, extern: "ntEqTime", tags: [], raises: [], noSideEffect, borrow.}- Returns true if a == b, that is if both times represent the same point in time. Source Edit
proc toTime(dt: DateTime): Time {.
tags: [], raises: [], gcsafe, locks: 0.}- Converts a broken-down time structure to calendar time representation. Source Edit
proc inZone(time: Time; zone: Timezone): DateTime {.
tags: [], raises: [], gcsafe, locks: 0.}- Break down time into a DateTime using zone as the timezone. Source Edit
proc inZone(dt: DateTime; zone: Timezone): DateTime {.
tags: [], raises: [], gcsafe, locks: 0.}- Convert dt into a DateTime using zone as the timezone. Source Edit
proc `$`(zone: Timezone): string {.
raises: [], tags: [].}- Returns the name of the timezone. Source Edit
proc `==`(zone1, zone2: Timezone): bool {.
raises: [], tags: [].}- Two Timezone's are considered equal if their name is equal. Source Edit
proc utc(): Timezone {.
raises: [], tags: [].}-
Get the Timezone implementation for the UTC timezone.
doAssert now().utc.timezone == utc() doAssert utc().name == "Etc/UTC"
Source Edit proc local(): Timezone {.
raises: [], tags: [].}-
Get the Timezone implementation for the local timezone.
doAssert now().timezone == local() doAssert local().name == "LOCAL"
Source Edit proc utc(dt: DateTime): DateTime {.
raises: [], tags: [].}- Shorthand for dt.inZone(utc()). Source Edit
proc local(dt: DateTime): DateTime {.
raises: [], tags: [].}- Shorthand for dt.inZone(local()). Source Edit
proc utc(t: Time): DateTime {.
raises: [], tags: [].}- Shorthand for t.inZone(utc()). Source Edit
proc local(t: Time): DateTime {.
raises: [], tags: [].}- Shorthand for t.inZone(local()). Source Edit
proc now(): DateTime {.
tags: [TimeEffect], gcsafe, locks: 0, raises: [Exception].}-
Get the current time as a DateTime in the local timezone.
Shorthand for getTime().local.
Source Edit proc initInterval(milliseconds, seconds, minutes, hours, days, months, years: int = 0): TimeInterval {.
raises: [], tags: [].}-
Creates a new TimeInterval.
You can also use the convenience procedures called milliseconds, seconds, minutes, hours, days, months, and years.
Example:
let day = initInterval(hours=24) let dt = initDateTime(01, mJan, 2000, 12, 00, 00, utc()) doAssert $(dt + day) == "2000-01-02T12-00-00+00:00"
Source Edit proc `+`(ti1, ti2: TimeInterval): TimeInterval {.
raises: [], tags: [].}- Adds two TimeInterval objects together. Source Edit
proc `-`(ti: TimeInterval): TimeInterval {.
raises: [], tags: [].}-
Reverses a time interval
let day = -initInterval(hours=24) echo day # -> (milliseconds: 0, seconds: 0, minutes: 0, hours: -24, days: 0, months: 0, years: 0)
Source Edit proc `-`(ti1, ti2: TimeInterval): TimeInterval {.
raises: [], tags: [].}-
Subtracts TimeInterval ti1 from ti2.
Time components are compared one-by-one, see output:
let a = fromUnix(1_000_000_000) let b = fromUnix(1_500_000_000) echo b.toTimeInterval - a.toTimeInterval # (milliseconds: 0, seconds: -40, minutes: -6, hours: 1, days: 5, months: -2, years: 16)
Source Edit proc `+`(dt: DateTime; interval: TimeInterval): DateTime {.
raises: [], tags: [].}-
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.
let dt = initDateTime(30, mMar, 2017, 00, 00, 00, utc()) doAssert $(dt + 1.months) == "2017-04-30T00:00:00+00:00" # This is correct and happens due to monthday overflow. doAssert $(dt - 1.months) == "2017-03-02T00:00:00+00:00"
Source Edit proc `-`(dt: DateTime; interval: TimeInterval): DateTime {.
raises: [], tags: [].}- Subtract 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. Source Edit
proc getDateStr(): string {.
gcsafe, extern: "nt$1", tags: [TimeEffect], raises: [Exception].}- Gets the current date as a string of the format YYYY-MM-DD. Source Edit
proc getClockStr(): string {.
gcsafe, extern: "nt$1", tags: [TimeEffect], raises: [Exception].}- Gets the current clock time as a string of the format HH:MM:SS. Source Edit
proc `$`(day: WeekDay): string {.
raises: [], tags: [].}- Stringify operator for WeekDay. Source Edit
proc `$`(m: Month): string {.
raises: [], tags: [].}- Stringify operator for Month. Source Edit
proc milliseconds(ms: int): TimeInterval {.
inline, raises: [], tags: [].}-
TimeInterval of ms milliseconds
Note: not all time procedures have millisecond resolution
Source Edit proc seconds(s: int): TimeInterval {.
inline, raises: [], tags: [].}-
TimeInterval of s seconds
echo getTime() + 5.second
Source Edit proc minutes(m: int): TimeInterval {.
inline, raises: [], tags: [].}-
TimeInterval of m minutes
echo getTime() + 5.minutes
Source Edit proc hours(h: int): TimeInterval {.
inline, raises: [], tags: [].}-
TimeInterval of h hours
echo getTime() + 2.hours
Source Edit proc days(d: int): TimeInterval {.
inline, raises: [], tags: [].}-
TimeInterval of d days
echo getTime() + 2.days
Source Edit proc months(m: int): TimeInterval {.
inline, raises: [], tags: [].}-
TimeInterval of m months
echo getTime() + 2.months
Source Edit proc years(y: int): TimeInterval {.
inline, raises: [], tags: [].}-
TimeInterval of y years
echo getTime() + 2.years
Source Edit proc `+=`(time: var Time; interval: TimeInterval) {.
raises: [], tags: [].}- Modifies time by adding interval. Source Edit
proc `+`(time: Time; interval: TimeInterval): Time {.
raises: [], tags: [].}-
Adds interval to time by converting to a DateTime in the local timezone, adding the interval, and converting back to Time.
echo getTime() + 1.day
Source Edit proc `-=`(time: var Time; interval: TimeInterval) {.
raises: [], tags: [].}- Modifies time by subtracting interval. Source Edit
proc `-`(time: Time; interval: TimeInterval): Time {.
raises: [], tags: [].}-
Subtracts interval from Time time.
echo getTime() - 1.day
Source Edit proc format(dt: DateTime; f: string): string {.
tags: [], raises: [ValueError].}-
This procedure formats dt as specified by f. The following format specifiers are available:
Specifier Description Example d Numeric value of the day of the month, it will be one or two digits long. 1/04/2012 -> 1, 21/04/2012 -> 21 dd Same as above, but always two digits. 1/04/2012 -> 01, 21/04/2012 -> 21 ddd Three letter string which indicates the day of the week. Saturday -> Sat, Monday -> Mon dddd Full string for the day of the week. Saturday -> Saturday, Monday -> Monday h The hours in one digit if possible. Ranging from 0-12. 5pm -> 5, 2am -> 2 hh The hours in two digits always. If the hour is one digit 0 is prepended. 5pm -> 05, 11am -> 11 H The hours in one digit if possible, randing from 0-24. 5pm -> 17, 2am -> 2 HH The hours in two digits always. 0 is prepended if the hour is one digit. 5pm -> 17, 2am -> 02 m The minutes in 1 digit if possible. 5:30 -> 30, 2:01 -> 1 mm Same as above but always 2 digits, 0 is prepended if the minute is one digit. 5:30 -> 30, 2:01 -> 01 M The month in one digit if possible. September -> 9, December -> 12 MM The month in two digits always. 0 is prepended. September -> 09, December -> 12 MMM Abbreviated three-letter form of the month. September -> Sep, December -> Dec MMMM Full month string, properly capitalized. September -> September s Seconds as one digit if possible. 00:00:06 -> 6 ss Same as above but always two digits. 0 is prepended. 00:00:06 -> 06 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. y(yyyy) This displays the year to different digits. You most likely only want 2 or 4 'y's yy Displays the year to two digits. 2012 -> 12 yyyy Displays the year to four digits. 2012 -> 2012 z Displays the timezone offset from UTC. GMT+7 -> +7, GMT-5 -> -5 zz Same as above but with leading 0. GMT+7 -> +07, GMT-5 -> -05 zzz Same as above but with :mm where mm represents minutes. GMT+7 -> +07:00, GMT-5 -> -05:00 Other strings can be inserted by putting them in ''. For example hh'->'mm will give 01->56. The following characters can be inserted without quoting them: : - ( ) / [ ] ,. However you don't need to necessarily separate format specifiers, a unambiguous format string like yyyyMMddhhmmss is valid too.
Source Edit proc `$`(dt: DateTime): string {.
tags: [], raises: [], gcsafe, locks: 0.}- Converts a DateTime object to a string representation. It uses the format yyyy-MM-dd'T'HH-mm-sszzz. Source Edit
proc `$`(time: Time): string {.
tags: [], raises: [], gcsafe, locks: 0.}- converts a Time value to a string representation. It will use the local time zone and use the format yyyy-MM-dd'T'HH-mm-sszzz. Source Edit
proc parse(value, layout: string; zone: Timezone = local()): DateTime {.
raises: [Exception, OverflowError, ValueError], tags: [TimeEffect].}-
This procedure parses a date/time string using the standard format identifiers as listed below. The procedure defaults information not provided in the format string from the running program (month, year, etc).
The return value will always be in the zone timezone. If no UTC offset was parsed, then the input will be assumed to be specified in the zone timezone already, so no timezone conversion will be done in that case.
Specifier Description Example d Numeric value of the day of the month, it will be one or two digits long. 1/04/2012 -> 1, 21/04/2012 -> 21 dd Same as above, but always two digits. 1/04/2012 -> 01, 21/04/2012 -> 21 ddd Three letter string which indicates the day of the week. Saturday -> Sat, Monday -> Mon dddd Full string for the day of the week. Saturday -> Saturday, Monday -> Monday h The hours in one digit if possible. Ranging from 0-12. 5pm -> 5, 2am -> 2 hh The hours in two digits always. If the hour is one digit 0 is prepended. 5pm -> 05, 11am -> 11 H The hours in one digit if possible, randing from 0-24. 5pm -> 17, 2am -> 2 HH The hours in two digits always. 0 is prepended if the hour is one digit. 5pm -> 17, 2am -> 02 m The minutes in 1 digit if possible. 5:30 -> 30, 2:01 -> 1 mm Same as above but always 2 digits, 0 is prepended if the minute is one digit. 5:30 -> 30, 2:01 -> 01 M The month in one digit if possible. September -> 9, December -> 12 MM The month in two digits always. 0 is prepended. September -> 09, December -> 12 MMM Abbreviated three-letter form of the month. September -> Sep, December -> Dec MMMM Full month string, properly capitalized. September -> September s Seconds as one digit if possible. 00:00:06 -> 6 ss Same as above but always two digits. 0 is prepended. 00:00:06 -> 06 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 Displays the year to two digits. 2012 -> 12 yyyy Displays the year to four digits. 2012 -> 2012 z Displays the timezone offset from UTC. Z is parsed as +0 GMT+7 -> +7, GMT-5 -> -5 zz Same as above but with leading 0. GMT+7 -> +07, GMT-5 -> -05 zzz Same as above but with :mm where mm represents minutes. GMT+7 -> +07:00, GMT-5 -> -05:00 Other strings can be inserted by putting them in ''. For example hh'->'mm will give 01->56. The following characters can be inserted without quoting them: : - ( ) / [ ] ,. However you don't need to necessarily separate format specifiers, a unambiguous format string like yyyyMMddhhmmss is valid too.
Source Edit proc countLeapYears(yearSpan: int): int {.
raises: [], tags: [].}-
Returns the number of leap years spanned by a given number of years.
Note: For leap years, start date is assumed to be 1 AD. counts the number of leap years up to January 1st of a given year. Keep in mind that if specified year is a leap year, the leap day has not happened before January 1st of that year.
Source Edit proc countDays(yearSpan: int): int {.
raises: [], tags: [].}- Returns the number of days spanned by a given number of years. Source Edit
proc countYears(daySpan: int): int {.
raises: [], tags: [].}- Returns the number of years spanned by a given number of days. Source Edit
proc countYearsAndDays(daySpan: int): tuple[years: int, days: int] {.
raises: [], tags: [].}- Returns the number of years spanned by a given number of days and the remainder as days. Source Edit
proc toTimeInterval(time: Time): TimeInterval {.
raises: [], tags: [].}-
Converts a Time to a TimeInterval.
To be used when diffing times.
let a = fromSeconds(1_000_000_000) let b = fromSeconds(1_500_000_000) echo a, " ", b # real dates echo a.toTimeInterval # meaningless value, don't use it by itself echo b.toTimeInterval - a.toTimeInterval # (milliseconds: 0, seconds: -40, minutes: -6, hours: 1, days: 5, months: -2, years: 16)
Source Edit proc initDateTime(monthday: MonthdayRange; month: Month; year: int; hour: HourRange; minute: MinuteRange; second: SecondRange; zone: Timezone = local()): DateTime {.
raises: [AssertionError], tags: [].}- Create a new DateTime in the specified timezone. Source Edit
proc getTime(): Time {.
tags: [TimeEffect], gcsafe, locks: 0, raises: [].}- Gets the current time as a Time with second resolution. Use epochTime for higher resolution. Source Edit
proc unixTimeToWinTime(time: CTime): int64 {.
raises: [], tags: [].}- converts a UNIX Time (time_t) to a Windows file time Source Edit
proc winTimeToUnixTime(time: int64): CTime {.
raises: [], tags: [].}- converts a Windows time to a UNIX Time (time_t) Source Edit
proc epochTime(): float {.
gcsafe, extern: "nt$1", tags: [TimeEffect], raises: [].}- 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). Source Edit
proc cpuTime(): float {.
gcsafe, extern: "nt$1", tags: [TimeEffect], raises: [].}-
gets time spent that the CPU spent to run the current process in seconds. This may be more useful for benchmarking than 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:
var t0 = cpuTime() doWork() echo "CPU time [s] ", cpuTime() - t0
Source Edit proc fromSeconds(since1970: float): Time {.
tags: [], raises: [], gcsafe, locks: 0, deprecated.}-
Takes a float which contains the number of seconds since the unix epoch and returns a time object.
Deprecated since v0.18.0: use fromUnix instead
Source Edit proc fromSeconds(since1970: int64): Time {.
tags: [], raises: [], gcsafe, locks: 0, deprecated.}-
Takes an int which contains the number of seconds since the unix epoch and returns a time object.
Deprecated since v0.18.0: use fromUnix instead
Source Edit proc toSeconds(time: Time): float {.
tags: [], raises: [], gcsafe, locks: 0, deprecated.}-
Returns the time in seconds since the unix epoch.
Deprecated since v0.18.0: use toUnix instead
Source Edit proc getLocalTime(time: Time): DateTime {.
tags: [], raises: [], gcsafe, locks: 0, deprecated.}-
Converts the calendar time time to broken-time representation, expressed relative to the user's specified time zone.
Deprecated since v0.18.0: use local instead
Source Edit proc getGMTime(time: Time): DateTime {.
tags: [], raises: [], gcsafe, locks: 0, deprecated.}-
Converts the calendar time time to broken-down time representation, expressed in Coordinated Universal Time (UTC).
Deprecated since v0.18.0: use utc instead
Source Edit proc getTimezone(): int {.
tags: [TimeEffect], raises: [], gcsafe, locks: 0, deprecated.}-
Returns the offset of the local (non-DST) timezone in seconds west of UTC.
Deprecated since v0.18.0: use now().utcOffset to get the current utc offset (including DST).
Source Edit proc timeInfoToTime(dt: DateTime): Time {.
tags: [], gcsafe, locks: 0, deprecated, raises: [].}-
Converts a broken-down time structure to calendar time representation.
Warning: This procedure is deprecated since version 0.14.0. Use toTime instead.
Source Edit proc getStartMilsecs(): int {.
deprecated, tags: [TimeEffect], gcsafe, locks: 0, raises: [].}- Source Edit
proc miliseconds(t: TimeInterval): int {.
deprecated, raises: [], tags: [].}- Source Edit
proc timeToTimeInterval(t: Time): TimeInterval {.
deprecated, raises: [], tags: [].}-
Converts a Time to a TimeInterval.
Warning: This procedure is deprecated since version 0.14.0. Use toTimeInterval instead.
Source Edit proc timeToTimeInfo(t: Time): DateTime {.
deprecated, raises: [], tags: [].}-
Converts a Time to DateTime.
Warning: This procedure is deprecated since version 0.14.0. Use inZone instead.
Source Edit proc getDayOfWeek(day, month, year: int): WeekDay {.
tags: [], raises: [], gcsafe, locks: 0, deprecated.}- Source Edit
proc getDayOfWeekJulian(day, month, year: int): WeekDay {.
deprecated, raises: [], tags: [].}- Returns the day of the week enum from day, month and year, according to the Julian calendar. Source Edit