Epoch in Lisp

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 Lisp.

(defun main ()
  ;; Use get-universal-time to get the current time in seconds since the Unix epoch
  (let ((now (get-universal-time)))
    (format t "~A~%" (local-time:now))
    
    ;; Print seconds since Unix epoch
    (format t "~A~%" now)
    
    ;; Print milliseconds since Unix epoch
    (format t "~A~%" (* now 1000))
    
    ;; Print nanoseconds since Unix epoch
    (format t "~A~%" (* now 1000000000))
    
    ;; Convert seconds back to a time object
    (format t "~A~%" (local-time:unix-to-timestamp now))
    
    ;; Convert nanoseconds back to a time object
    (format t "~A~%" (local-time:unix-to-timestamp (floor (/ (* now 1000000000) 1000000000))
                                                   :nsec (mod (* now 1000000000) 1000000000)))))

(main)

To run this program, you’ll need to install and load the local-time library, which provides more comprehensive time manipulation functions than the built-in Common Lisp time functions.

$ sbcl --load epoch.lisp
2023-06-01T12:34:56.789012+00:00
1685623696
1685623696000
1685623696000000000
@2023-06-01T12:34:56.000000+00:00
@2023-06-01T12:34:56.000000000+00:00

In this Lisp version:

  1. We use get-universal-time to get the current time in seconds since the Unix epoch.
  2. The local-time:now function from the local-time library gives us a timestamp object similar to Go’s time.Now().
  3. We multiply the seconds by 1000 and 1000000000 to get milliseconds and nanoseconds respectively.
  4. We use local-time:unix-to-timestamp to convert seconds back to a timestamp object.
  5. For nanosecond precision, we split the nanoseconds into seconds and remaining nanoseconds.

Note that Common Lisp doesn’t have built-in functions for millisecond or nanosecond precision time, so we’re simulating them by multiplying the second value. For more precise timing, you might need to use system-specific functions or additional libraries.

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