Epoch in Prolog

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

:- use_module(library(system)).

main :-
    % Get the current time
    get_time(Now),
    format('Current time: ~w~n', [Now]),

    % Get seconds since Unix epoch
    Seconds is floor(Now),
    format('Seconds since Unix epoch: ~w~n', [Seconds]),

    % Get milliseconds since Unix epoch
    Milliseconds is floor(Now * 1000),
    format('Milliseconds since Unix epoch: ~w~n', [Milliseconds]),

    % Get nanoseconds since Unix epoch
    Nanoseconds is floor(Now * 1000000000),
    format('Nanoseconds since Unix epoch: ~w~n', [Nanoseconds]),

    % Convert seconds back to a datetime
    stamp_date_time(Seconds, DateTime, 'UTC'),
    format_time(atom(FormattedTime), '%Y-%m-%d %H:%M:%S', DateTime),
    format('Converted back from seconds: ~w~n', [FormattedTime]),

    % Convert nanoseconds back to a datetime
    NanoDateTime is Nanoseconds / 1000000000,
    stamp_date_time(NanoDateTime, NanoDate, 'UTC'),
    format_time(atom(NanoFormattedTime), '%Y-%m-%d %H:%M:%S.%f', NanoDate),
    format('Converted back from nanoseconds: ~w~n', [NanoFormattedTime]).

To run the program, save it as epoch.pl and use the Prolog interpreter:

$ swipl -s epoch.pl -g main -t halt
Current time: 1651234567.890123
Seconds since Unix epoch: 1651234567
Milliseconds since Unix epoch: 1651234567890
Nanoseconds since Unix epoch: 1651234567890123000
Converted back from seconds: 2022-04-29 12:36:07
Converted back from nanoseconds: 2022-04-29 12:36:07.890123

In this Prolog implementation:

  1. We use the get_time/1 predicate to get the current time as a float representing seconds since the Unix epoch.
  2. We use simple arithmetic to convert the time to seconds, milliseconds, and nanoseconds.
  3. The stamp_date_time/3 predicate is used to convert a timestamp back to a datetime structure.
  4. The format_time/3 predicate is used to format the datetime into a human-readable string.

Note that Prolog doesn’t have built-in functions for milliseconds and nanoseconds precision like some other languages, so we’re simulating them by multiplying the seconds value. The actual precision may vary depending on your Prolog implementation and system.

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