Epoch in Wolfram Language

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 Wolfram Language.

(* Use AbsoluteTime[] to get the current time *)
now = AbsoluteTime[];
Print[DateString[now]];

(* Convert to Unix timestamp (seconds since epoch) *)
unixTime = Round[now - AbsoluteTime[{1970, 1, 1, 0, 0, 0}]];
Print[unixTime];

(* Convert to milliseconds *)
unixTimeMillis = Round[1000 * (now - AbsoluteTime[{1970, 1, 1, 0, 0, 0}])];
Print[unixTimeMillis];

(* Convert to nanoseconds *)
unixTimeNanos = Round[1000000000 * (now - AbsoluteTime[{1970, 1, 1, 0, 0, 0}])];
Print[unixTimeNanos];

(* Convert Unix timestamp back to Wolfram Language date *)
Print[DateString[AbsoluteTime[{1970, 1, 1, 0, 0, 0}] + unixTime]];

(* Convert Unix timestamp with nanoseconds back to Wolfram Language date *)
Print[DateString[AbsoluteTime[{1970, 1, 1, 0, 0, 0}] + unixTimeNanos/1000000000]];

In Wolfram Language, we use AbsoluteTime[] to get the current time. We can then perform calculations to convert this to Unix time (seconds, milliseconds, or nanoseconds since the Unix epoch).

To get the Unix timestamp, we subtract the absolute time of the Unix epoch (January 1, 1970, 00:00:00 UTC) from the current time.

For milliseconds and nanoseconds, we multiply this difference by 1000 and 1000000000 respectively.

We can also convert Unix timestamps back to Wolfram Language dates using AbsoluteTime[] and DateString[].

Here’s an example of what the output might look like:

Sun 5 Mar 2023 15:30:45
1678030245
1678030245000
1678030245000000000
Sun 5 Mar 2023 15:30:45
Sun 5 Mar 2023 15:30:45

Note that the exact output will depend on when you run the code.

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