Files
monitor/scripts/00_dyear_to_date.py
2025-10-09 19:57:47 +03:00

33 lines
1.1 KiB
Python
Executable File

from datetime import datetime, timedelta
def decimal_year_to_date(decimal_year):
"""
Converts a decimal year (e.g., 2024.5) to a datetime object.
"""
year = int(decimal_year)
fractional_year = decimal_year - year
# Determine if it's a leap year to get the correct number of days
is_leap_year = (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0)
days_in_year = 366 if is_leap_year else 365
# Calculate the day of the year (1-indexed)
day_of_year = int(fractional_year * days_in_year) + 1
# Create a datetime object for January 1st of the given year
start_of_year = datetime(year, 1, 1)
# Add the calculated number of days to get the final date
result_date = start_of_year + timedelta(days=day_of_year - 1)
return result_date
# Example usage:
decimal_year_example = 2020.9181
date_result = decimal_year_to_date(decimal_year_example)
print(f"Decimal year {decimal_year_example} converts to: {date_result}")
decimal_year_example_2 = 2021.8271
date_result_2 = decimal_year_to_date(decimal_year_example_2)
print(f"Decimal year {decimal_year_example_2} converts to: {date_result_2}")