To team players who are within five blocks of one another who don't currently have a team:
In a repeating command block:
execute as @a[team=] at @s if @a[team=,distance=1..5,limit=1] run execute as @a[distance=..5,limit=2] run team join <team name> @s
What this does is it executes as a player who has no team at that player if there is a single player within 1 to 5 blocks away who also doesn't have a team. It runs another execute function which executes as both players joining them both to a team. If you want to randomize which team they join try something like this:
Setup a scoreboard to track the current time:
/scoreboard objectives add time dummy
In a repeating command block set the scoreboard to the current time:
execute store result score @a time run time query daytime
In a number of similar repeating command blocks set a particular team depending on the current time: in this example green is for 1000 to 2000:
execute as @a[team=] at @s if @a[team=,distance=1..5,limit=1] run execute as @a[distance=..5,limit=2] if score @s time matches 1000..2000 run team join green @s
You'd need a different command block for each team and time.