Изучение различных методов расчета возраста принца Эндрю

Принц Эндрю, также известный как Его Королевское Высочество герцог Йоркский, является видным членом британской королевской семьи. Если вам интересно узнать, как определить возраст принца Эндрю программно, в этой статье будут рассмотрены различные методы достижения этой цели. Мы предоставим примеры кода на Python для демонстрации каждого метода. Итак, давайте углубимся и посчитаем возраст принца Андрея!

Метод 1: использование текущей даты и даты рождения
Этот метод предполагает вычитание даты рождения принца Эндрю из текущей даты для расчета его возраста.

from datetime import datetime
def calculate_age(birth_date):
    current_date = datetime.now()
    age = current_date.year - birth_date.year
    if current_date.month < birth_date.month or (current_date.month == birth_date.month and current_date.day < birth_date.day):
        age -= 1
    return age
# Prince Andrew's birth date: February 19, 1960
prince_andrew_birth_date = datetime(1960, 2, 19)
prince_andrew_age = calculate_age(prince_andrew_birth_date)
print("Prince Andrew's age:", prince_andrew_age)

Метод 2. Использование библиотеки дат.
Другой подход — использовать библиотеку дат, например библиотеку dateutil, которая предоставляет удобные функции для работы с датами.

from datetime import datetime
from dateutil.relativedelta import relativedelta
def calculate_age(birth_date):
    current_date = datetime.now()
    age = relativedelta(current_date, birth_date).years
    return age
# Prince Andrew's birth date: February 19, 1960
prince_andrew_birth_date = datetime(1960, 2, 19)
prince_andrew_age = calculate_age(prince_andrew_birth_date)
print("Prince Andrew's age:", prince_andrew_age)

Метод 3. Использование библиотеки Arrow
Библиотека Arrow обеспечивает лаконичный и выразительный способ работы с датами и временем.

import arrow
def calculate_age(birth_date):
    current_date = arrow.now()
    age = current_date.year - birth_date.year
    if current_date.month < birth_date.month or (current_date.month == birth_date.month and current_date.day < birth_date.day):
        age -= 1
    return age
# Prince Andrew's birth date: February 19, 1960
prince_andrew_birth_date = arrow.get('1960-02-19')
prince_andrew_age = calculate_age(prince_andrew_birth_date)
print("Prince Andrew's age:", prince_andrew_age)

Метод 4. Использование библиотеки Pendulum
Pendulum – это библиотека, упрощающая работу с датами и временем.

import pendulum
def calculate_age(birth_date):
    current_date = pendulum.now()
    age = current_date.year - birth_date.year
    if current_date.month < birth_date.month or (current_date.month == birth_date.month and current_date.day < birth_date.day):
        age -= 1
    return age
# Prince Andrew's birth date: February 19, 1960
prince_andrew_birth_date = pendulum.datetime(1960, 2, 19)
prince_andrew_age = calculate_age(prince_andrew_birth_date)
print("Prince Andrew's age:", prince_andrew_age)