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.

extends Node

func _ready():
    # Use OS.get_unix_time() to get elapsed time since the Unix epoch in seconds
    var now = OS.get_unix_time()
    print(OS.get_datetime_from_unix_time(now))
    
    print(now)
    print(now * 1000)  # Milliseconds
    print(now * 1000000000)  # Nanoseconds
    
    # You can also convert integer seconds since the epoch into the corresponding datetime
    print(OS.get_datetime_from_unix_time(now))
    
    # Note: GDScript doesn't have a built-in way to get nanosecond precision,
    # so we're using seconds and multiplying for milliseconds and nanoseconds

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:

{year:2023, month:6, day:15, weekday:4, hour:12, minute:34, second:56}
1686831296
1686831296000
1686831296000000000
{year:2023, month:6, day:15, weekday:4, hour:12, minute:34, second:56}

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.