Skip to content

Function `baltic.decimalDate`

Barney Potter edited this page Oct 14, 2024 · 1 revision

decimalDate() Function

Description

The decimalDate() function in BALTIC converts calendar dates in a specified format to a decimal date representation. A decimal date represents the fraction of the year that has passed by the given date.

Syntax

def decimalDate(date, fmt="%Y-%m-%d", variable=False)

Parameters

  • date (str): The date to be converted.
  • fmt (str): The format of the input date string. Default is "%Y-%m-%d".
  • variable (bool): If True, allows for variable date precision. Default is False.

Return Value

  • float: The decimal representation of the date.

Functionality

  1. Parses the input date string according to the specified format.
  2. If variable is True, adjusts the format to match the available precision in the date.
  3. Converts the date to a datetime object.
  4. Calculates the fraction of the year that has passed up to the given date.
  5. Returns the year plus this fraction as a decimal number.

Use Cases

  1. Converting dates to a continuous numerical representation for time-based analyses.
  2. Handling dates with different levels of precision in a single dataset.
  3. Preparing date data for plotting on a continuous time axis.
  4. Performing date arithmetic or comparisons.

Example

import baltic as bt

# Basic usage
print(bt.decimalDate("2023-05-23"))
# Output: 2023.3890410958904

# Using variable precision
print(bt.decimalDate("2023", fmt="%Y", variable=True))
# Output: 2023.0

print(bt.decimalDate("2023-05", fmt="%Y-%m", variable=True))
# Output: 2023.3306849315068

# Custom date format
print(bt.decimalDate("23/05/2023", fmt="%d/%m/%Y"))
# Output: 2023.3890410958904

Notes

  • When variable is True, the function can handle dates with different levels of precision:
    • A year-only date (e.g., "2023") will be interpreted as January 1st of that year.
    • A year-month date (e.g., "2023-05") will be interpreted as the first day of that month.
  • The function uses the total seconds in the year to calculate the decimal portion, accounting for leap years.
  • If the input date string doesn't match the specified format, a ValueError will be raised.
  • This function is particularly useful in phylogenetic analyses where a continuous representation of time is needed.
Clone this wiki locally