Epoch in GDScript
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 GDScript.
To run this script, save it as a .gd
file and attach it to a Node in your Godot project. When you run the scene, you’ll see output similar to this:
In GDScript, we use the OS.get_unix_time()
function to get the current Unix timestamp in seconds. We can then use OS.get_datetime_from_unix_time()
to convert this timestamp into a dictionary representing the date and time.
For milliseconds and nanoseconds, we simply multiply the seconds value, as GDScript doesn’t provide built-in functions for these precisions.
Note that unlike some other languages, GDScript doesn’t have a separate Date/Time type. Instead, it uses dictionaries to represent date and time information.
Next, we’ll look at another time-related task: time parsing and formatting.