Epoch in Nim

A common requirement in programs is getting the number of seconds, milliseconds, or nanoseconds since the Unix epoch. Here’s how to do it in Nim.

import times

proc main() =
  # Use `getTime()` to get the current time
  let now = getTime()
  echo now

  # Convert to seconds, milliseconds, and nanoseconds since the Unix epoch
  echo now.toUnix()
  echo now.toUnixFloat() * 1000
  echo now.toUnixFloat() * 1_000_000_000

  # You can also convert integer seconds or nanoseconds
  # since the epoch into the corresponding Time
  echo fromUnix(now.toUnix())
  echo fromUnixFloat(now.toUnixFloat())

main()

Use getTime() to get the current time. Then, you can use toUnix(), toUnixFloat() to get elapsed time since the Unix epoch in seconds or as a floating-point number of seconds, respectively. To get milliseconds or nanoseconds, multiply the float result by 1000 or 1_000_000_000.

You can also convert integer seconds or floating-point seconds since the epoch into the corresponding Time using fromUnix() or fromUnixFloat().

When you run this program, you’ll see output similar to this:

$ nim c -r epoch.nim
2023-05-31T12:34:56+00:00
1685535296
1685535296000
1685535296000000000
2023-05-31T12:34:56+00:00
2023-05-31T12:34:56+00:00

Next, we’ll look at another time-related task: time parsing and formatting.