How to get posts and comments amount per hour, per year and per month?

For comments:

function count_comments_in_period( $date_from, $date_to ){
    global $wpdb;
    $count = $wpdb->get_var( $wpdb->prepare("SELECT COUNT(*) FROM {$wpdb->comments} WHERE comment_date >= %s  AND comment_date < %s ", $date_from, $date_to));
    return $count;
}

Just use dates in yyyy-mm-dd format.

For posts:

function count_posts_in_period( $date_from, $date_to ){
    global $wpdb;
    $count = $wpdb->get_var( $wpdb->prepare("SELECT COUNT(*) FROM {$wpdb->posts} WHERE post_date >= %s  AND post_date < %s ", $date_from, $date_to));
    return $count;
}