How to get the post ID when creating JS variables with localize_script

You should declare global $post; before attempting to access this variable, but to answer your question regarding when it is created, the ‘wp’ action hook is the safest bet.

As such I’d suggest the following in your functions.php file as a simple solution

function my_localize_post_id(){
   global $post;
    wp_register_script( 'your_script'... /** other parameters required here **/ );
    wp_localize_script( 'your_script', 'the_name_for_your_js_object' , array( 'post_id'=>$post->ID ) );
}

add_action( 'wp', 'my_localize_post_id' );