how to calculate distance between galaxies in the distant past
I'm assuming you're talking about physical distances (as opposed to any of the other distance measures in cosmology).

The comoving distance to a galaxy at redshift $z$ is
$$
d_C(z) = \frac{c}{H_0}\int_0^z 
         \frac{dz}{\sqrt{
         \Omega_r(1+z)^4 + 
         \Omega_m(1+z)^3 + 
         \Omega_k(1+z)^2 + 
         \Omega_\Lambda
         }},
$$
where $c$ and $H_0$ are the speed of light and the Hubble parameter, and
$\{\Omega_r,\Omega_m,\Omega_k,\Omega_\Lambda\}$ $\simeq$ $\{\lt 10^{-4},0.3,0,0.7\}$
are the radiation, matter, curvature, and dark energy density parameters, respectively.

By definition, the comoving and the physical distance $d_P$ coincide today, but at the time a galaxy at $z$ emitted the light we see today, it was at
$$
d_P = \frac{d_C}{1+z}.
$$

In your example, $z_A = 6$, and $z_B = 0.5$. The comoving distance to galaxy $B$ is, from the equation above and with a Planck Collaboration et al. (2016) cosmology, $1946\,\mathrm{Mpc}$ away. Hence, when $A$ emitted the light we see today, its physical distance was a factor $(1+6)$ smaller, i.e. $278\,\mathrm{Mpc}$.



In Python, with astropy:

from astropy.cosmology import Planck15
from astropy import units as u
zA,zB      = 6,.5
dC_B       = Planck15.comoving_distance(zB)
dP_B_at_zA = dC_B / (1+zA)
print(dC_B)
   -&gt; 1945.5612969107992 Mpc
print(dP_B_at_zA)
   -&gt; 277.93732813011417 Mpc
print(dP_B_at_zA.to(u.Mlyr)) # convert to light-years
   -&gt; 906.5103217447773 Mlyr