date_convertions¶
shortfx.fxDate.date_convertions
¶
Date and time conversion module.
This module provides comprehensive functions for converting between different date/time formats including: datetime objects, strings, timestamps, ISO formats, timezones, Julian dates, Windows FILETIME, and Active Directory formats. All functions handle timezone-aware and timezone-naive datetime objects appropriately.
Functions¶
ad_format_to_datetime(p_ad_date_str: str) -> datetime
¶
Convierte una cadena de fecha/hora en formato 'YYYYMMDDHHMMSS.0Z' (usado en Active Directory) a un objeto datetime de Python (timezone-aware y en UTC).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
p_ad_date_str
|
str
|
La cadena de fecha/hora en formato 'YYYYMMDDHHMMSS.0Z'. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
datetime |
datetime
|
Un objeto datetime que representa la fecha y hora en UTC. |
Raises:
| Type | Description |
|---|---|
ValueError
|
Si la cadena de entrada no coincide con el formato esperado. |
TypeError
|
Si la entrada no es una cadena. |
Source code in shortfx/fxDate/date_convertions.py
convert_timezone(dt: datetime, from_tz: str, to_tz: str) -> datetime
¶
Converts a datetime between two IANA timezones.
If the input datetime is naive it is assumed to belong to from_tz.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dt
|
datetime
|
The datetime to convert. |
required |
from_tz
|
str
|
Source timezone name (e.g. |
required |
to_tz
|
str
|
Target timezone name (e.g. |
required |
Returns:
| Type | Description |
|---|---|
datetime
|
A timezone-aware datetime in the target timezone. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If dt is not a datetime object. |
Example
from datetime import datetime convert_timezone(datetime(2026, 4, 4, 12, 0), "UTC", "Europe/Madrid") datetime.datetime(2026, 4, 4, 14, 0, tzinfo=zoneinfo.ZoneInfo(key='Europe/Madrid'))
Complexity: O(1)
Source code in shortfx/fxDate/date_convertions.py
date_to_excel_serial(d: Union[date, datetime]) -> int
¶
Converts a Python date to an Excel serial date number.
Description
Returns the serial number compatible with Excel's 1900 date
system. Accounts for the Lotus 1-2-3 leap year bug so that
round-tripping through excel_serial_to_date is consistent.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
d
|
Union[date, datetime]
|
A |
required |
Returns:
| Type | Description |
|---|---|
int
|
Excel serial date number (integer). |
Raises:
| Type | Description |
|---|---|
TypeError
|
If d is not a |
ValueError
|
If d is before 1900-01-01. |
Usage Example
from datetime import date date_to_excel_serial(date(2023, 1, 1)) 44927
Complexity: O(1)
Source code in shortfx/fxDate/date_convertions.py
date_to_excel_timestamp(dt_val: datetime) -> float
¶
Converts a datetime to an Excel serial number including fractional day.
Excel serial day 1 = 1900-01-01. The fractional part represents the time of day (e.g. 0.5 = noon).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dt_val
|
datetime
|
A datetime object. |
required |
Returns:
| Type | Description |
|---|---|
float
|
Excel serial number with fractional day component. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If dt_val is not a datetime. |
ValueError
|
If date is before 1900-01-01. |
Example
from datetime import datetime date_to_excel_timestamp(datetime(2026, 4, 8, 12, 0, 0)) 46113.5
Complexity: O(1)
Source code in shortfx/fxDate/date_convertions.py
date_to_human_short(dt_value: Union[date, datetime], language: str = 'en') -> str
¶
Formats a date as a short human-readable string.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dt_value
|
Union[date, datetime]
|
The date or datetime to format. |
required |
language
|
str
|
|
'en'
|
Returns:
| Type | Description |
|---|---|
str
|
A short formatted date string. |
Example
from datetime import date date_to_human_short(date(2026, 4, 4), "en") 'Apr 4, 2026' date_to_human_short(date(2026, 4, 4), "es") '4 abr. 2026'
Complexity: O(1)
Source code in shortfx/fxDate/date_convertions.py
date_to_iso_format(date_input: Union[datetime, str], input_format: str = None) -> str
¶
Converts a datetime object to an ISO 8601 formatted string.
ISO 8601 is an international standard for representing dates and times, ensuring clarity and interoperability across different systems and locales. The common format is YYYY-MM-DDTHH:MM:SS.ffffff+HH:MM (date, 'T', time, microseconds, and timezone offset).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
date_input
|
Union[datetime, str]
|
The date to convert.
Can be a datetime object (e.g., |
required |
input_format
|
str
|
The format code string for |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
The date represented as an ISO 8601 formatted string. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If |
ValueError
|
If |
Example
from datetime import datetime, timezone
Example with a naive datetime object (no timezone)¶
date_to_iso_format(datetime(2023, 1, 15, 10, 30, 45, 123456)) '2023-01-15T10:30:45.123456'
Example with a timezone-aware datetime object (recommended for robustness)¶
dt_utc = datetime(2023, 1, 15, 10, 30, 45, 123456, tzinfo=timezone.utc) date_to_iso_format(dt_utc) '2023-01-15T10:30:45.123456+00:00'
Example with a date-only datetime object¶
date_to_iso_format(datetime(2024, 7, 20).date()) # Convert to datetime first '2024-07-20T00:00:00'
Example with string input¶
date_to_iso_format("2023-05-10 08:00:00", "%Y-%m-%d %H:%M:%S") '2023-05-10T08:00:00'
Example of an invalid input (string without format)¶
try: date_to_iso_format("2023-05-10") except ValueError as e: print(f"Error: {e}")
Expected output: Error: 'input_format' is required when 'date_input' is a string.¶
Cost: O(1)
Source code in shortfx/fxDate/date_convertions.py
date_to_iso_week_date(d: Union[date, datetime]) -> str
¶
Convert a date to an ISO 8601 week date string.
Description
Returns the date in YYYY-Www-D format, where YYYY is the
ISO week-numbering year, ww is the week number (01–53), and
D is the day of the week (1=Monday, 7=Sunday).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
d
|
Union[date, datetime]
|
A |
required |
Returns:
| Type | Description |
|---|---|
str
|
ISO week date string (e.g. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If d is not a |
Usage Example
from datetime import date date_to_iso_week_date(date(2023, 1, 2)) '2023-W01-1'
Complexity: O(1)
Source code in shortfx/fxDate/date_convertions.py
date_to_julian(date_input: Union[datetime, str], input_format: Optional[str] = None) -> int
¶
Convierte una fecha estándar a su representación de fecha Juliana (día del año).
Problema/Necesidad del Usuario: Para ciertos sistemas antiguos o en astronomía, las fechas se representan como el número de día del año (ej. el día 32 es el 1 de Febrero). Es necesario convertir fechas comunes a este formato.
Objetivos del Producto: Proporcionar una forma sencilla de obtener el "día del año" para una fecha dada, facilitando la integración con sistemas que utilizan este formato.
Descripción: Dada una fecha (como objeto datetime o cadena de texto),
esta función devuelve el número del día dentro de ese año. Enero 1 es el día 1,
Febrero 1 es el día 32 (o 33 en un año bisiesto), etc.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
date_input
|
Union[datetime, str]
|
La fecha a convertir. Puede ser un objeto
|
required |
input_format
|
str
|
El formato de cadena de fecha (ej. '%Y-%m-%d') si 'date_input' es una cadena. Es obligatorio si 'date_input' es una cadena. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
int |
int
|
El número del día del año (1 a 365 o 366). |
Raises:
| Type | Description |
|---|---|
TypeError
|
Si 'date_input' no es un objeto |
ValueError
|
Si 'date_input' es una cadena y 'input_format' es |
Example
from datetime import datetime
Ejemplo 1: Enero 1, 2025 (siempre día 1)¶
date_to_julian(datetime(2025, 1, 1)) 1
Ejemplo 2: Febrero 1, 2025 (año no bisiesto)¶
date_to_julian(datetime(2025, 2, 1)) 32 # 31 días de Enero + 1 día de Febrero
Ejemplo 3: Marzo 1, 2024 (año bisiesto)¶
date_to_julian(datetime(2024, 3, 1)) 61 # 31 (Ene) + 29 (Feb 2024) + 1 (Mar) = 61
Ejemplo 4: 31 de Diciembre de un año común¶
date_to_julian(datetime(2023, 12, 31)) 365
Ejemplo 5: 31 de Diciembre de un año bisiesto¶
date_to_julian(datetime(2024, 12, 31)) 366
Ejemplo 6: Usando cadena de fecha¶
date_to_julian("2025-06-15", "%Y-%m-%d") 166 # Día 166 del año 2025
Cost: O(1)
Source code in shortfx/fxDate/date_convertions.py
605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 | |
date_to_string(date_input: datetime, format_code: str = '%Y-%m-%d') -> str
¶
Converts a datetime object into a formatted string.
Description
Formats a datetime object as a string using Python's strftime format codes. Useful for displaying dates in human-readable formats or for system integration requiring specific date string conventions.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
date_input
|
datetime
|
The datetime object to convert to a string. |
required |
format_code
|
str
|
The format code string (e.g., '%Y-%m-%d', '%d/%m/%Y %H:%M:%S'). Defaults to '%Y-%m-%d'. |
'%Y-%m-%d'
|
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
The formatted date string. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If 'date_input' is not a datetime object. |
Usage Example
from datetime import datetime from shortfx.fxDate.date_convertions import date_to_string my_date = datetime(2026, 1, 3, 14, 30, 45) date_to_string(my_date) # Default format '2026-01-03' date_to_string(my_date, '%d/%m/%Y') # European format '03/01/2026' date_to_string(my_date, '%Y-%m-%d %H:%M:%S') # With time '2026-01-03 14:30:45'
Cost: O(1)
Source code in shortfx/fxDate/date_convertions.py
datetime_to_ad_format(p_dt_input: Union[datetime, date]) -> str
¶
Convierte un objeto datetime o date a la cadena de formato 'YYYYMMDDHHMMSS.0Z' utilizada en Active Directory para atributos como 'whenCreated'.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
p_dt_input
|
Union[datetime, date]
|
El objeto datetime o date a convertir.
Si es un objeto |
required |
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
La fecha y hora formateada como 'YYYYMMDDHHMMSS.0Z'. |
Raises:
| Type | Description |
|---|---|
TypeError
|
Si la entrada no es un objeto datetime ni date. |
Source code in shortfx/fxDate/date_convertions.py
datetime_to_cron(dt_input: Union[datetime, date]) -> str
¶
Convert a datetime to a cron schedule expression.
Produces a cron string matching the exact minute, hour, day, month.
The day-of-week field is * (any).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dt_input
|
Union[datetime, date]
|
Datetime (or date, which defaults to midnight). |
required |
Returns:
| Type | Description |
|---|---|
str
|
Cron expression string |
Example
from datetime import datetime datetime_to_cron(datetime(2025, 6, 15, 14, 30)) '30 14 15 6 *'
Complexity: O(1)
Source code in shortfx/fxDate/date_convertions.py
datetime_to_date(datetime_obj: datetime) -> date
¶
Converts a datetime object to a date object, discarding time components.
Description
Extracts only the date portion (year, month, day) from a datetime object, removing all time information (hour, minute, second, microsecond). Useful for date-only comparisons and storage.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
datetime_obj
|
datetime
|
The datetime object to convert. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
date |
date
|
A new date object representing the date part of the input datetime. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If 'datetime_obj' is not a datetime object. |
Usage Example
from datetime import datetime, date from shortfx.fxDate.date_convertions import datetime_to_date dt_with_time = datetime(2026, 1, 3, 14, 30, 45) date_only = datetime_to_date(dt_with_time) print(date_only) 2026-01-03 print(type(date_only))
Cost: O(1)
Source code in shortfx/fxDate/date_convertions.py
datetime_to_filetime(p_dt: Union[datetime, date]) -> int
¶
Convierte un objeto datetime o date de Python a un valor FILETIME de Windows.
FILETIME es el número de intervalos de 100 nanosegundos transcurridos desde el 1 de enero de 1601, 00:00:00 UTC.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
p_dt
|
Union[datetime, date]
|
El objeto datetime o date a convertir. Si es un objeto date, se tratará como medianoche (00:00:00) UTC de ese día. Si es un objeto datetime naive, se asumirá que está en UTC. Si es un objeto datetime timezone-aware, se convertirá a UTC. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
int |
int
|
El valor FILETIME como un entero de 64 bits. |
Raises:
| Type | Description |
|---|---|
TypeError
|
Si p_dt no es un objeto datetime ni date. |
Source code in shortfx/fxDate/date_convertions.py
datetime_to_integer(date_input: Union[datetime, date, str], input_format: str = None) -> int
¶
Converts a date to an integer in YYYYMMDD format, ignoring time.
Description
Transforms a date into an integer representation (YYYYMMDD) for compact storage and easy numerical comparisons. Time components are ignored. Accepts datetime, date objects, or strings.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
date_input
|
Union[datetime, date, str]
|
The date to convert. Can be datetime, date, or string. |
required |
input_format
|
str
|
Format code if 'date_input' is a string. Required when 'date_input' is a string. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
int |
int
|
The date as YYYYMMDD integer (e.g., 20260103). |
Raises:
| Type | Description |
|---|---|
TypeError
|
If 'date_input' is not datetime, date, or string. |
ValueError
|
If 'date_input' is string and 'input_format' not provided, or if parsing fails. |
Usage Example
from datetime import datetime, date from shortfx.fxDate.date_convertions import datetime_to_integer datetime_to_integer(datetime(2026, 1, 3)) 20260103 datetime_to_integer(date(2026, 1, 3)) 20260103 datetime_to_integer("03/01/2026", "%d/%m/%Y") 20260103
Cost: O(1)
Source code in shortfx/fxDate/date_convertions.py
datetime_to_iso8601(dt: Union[date, datetime]) -> str
¶
Converts a date or datetime to an ISO 8601 string.
Description
Returns the YYYY-MM-DD form for date objects and
YYYY-MM-DDTHH:MM:SS (with optional timezone) for
datetime objects.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dt
|
Union[date, datetime]
|
A |
required |
Returns:
| Type | Description |
|---|---|
str
|
ISO 8601 formatted string. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If dt is not a |
Usage Example
from datetime import date datetime_to_iso8601(date(2024, 3, 15)) '2024-03-15'
Complexity: O(1)
Source code in shortfx/fxDate/date_convertions.py
datetime_to_milliseconds_timestamp(date_input: datetime) -> int
¶
Convierte un objeto datetime a un sello de tiempo Unix en milisegundos.
Problema/Necesidad del Usuario: Muchos sistemas modernos (APIs, bases de datos NoSQL, sistemas de logging de alto rendimiento) utilizan sellos de tiempo en milisegundos en lugar de segundos para una mayor granularidad. Es crucial poder convertir datetime a este formato.
Objetivos del Producto: Facilitar la integración con sistemas que requieren sellos de tiempo de milisegundos, mejorando la compatibilidad y la precisión en el registro de eventos.
Descripción: Esta función toma un objeto datetime y lo convierte en el número de
milisegundos transcurridos desde la Época Unix (1 de enero de 1970, 00:00:00 UTC).
Asegúrate de que tu objeto datetime tenga información de zona horaria (UTC preferiblemente)
para evitar ambigüedades.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
date_input
|
datetime
|
El objeto |
required |
Returns:
| Name | Type | Description |
|---|---|---|
int |
int
|
El sello de tiempo Unix en milisegundos. |
Raises:
| Type | Description |
|---|---|
TypeError
|
Si 'date_input' no es un objeto |
Example
from datetime import datetime, timezone dt_utc = datetime(2025, 6, 11, 1, 58, 11, 123456, tzinfo=timezone.utc) datetime_to_milliseconds_timestamp(dt_utc) 1749597491123
Si el datetime no tiene información de zona horaria, se asume UTC¶
dt_naive = datetime(2025, 6, 11, 1, 58, 11, 123456) datetime_to_milliseconds_timestamp(dt_naive) # Se comportará como si fuera UTC 1749597491123
Cost: O(1)
Source code in shortfx/fxDate/date_convertions.py
datetime_to_rfc2822(dt_input: Union[datetime, date]) -> str
¶
Format a datetime as an RFC 2822 string (email header format).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dt_input
|
Union[datetime, date]
|
Datetime or date to format. |
required |
Returns:
| Type | Description |
|---|---|
str
|
RFC 2822 formatted string (e.g. |
Example
from datetime import datetime datetime_to_rfc2822(datetime(2025, 6, 15, 14, 30, 0)) 'Sun, 15 Jun 2025 14:30:00 +0000'
Complexity: O(1)
Source code in shortfx/fxDate/date_convertions.py
datetime_to_timestamp(date_input: datetime) -> float
¶
Converts a datetime object to a Unix timestamp.
Description
Converts a datetime to Unix timestamp (seconds since epoch: January 1, 1970, 00:00:00 UTC). Best used with timezone-aware datetime objects in UTC. Naive datetimes are treated as local time.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
date_input
|
datetime
|
The datetime object to convert. Recommended to be timezone-aware (preferably UTC) for accuracy. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
float |
float
|
The Unix timestamp as a float (seconds since epoch). |
Raises:
| Type | Description |
|---|---|
TypeError
|
If 'date_input' is not a datetime object. |
Usage Example
from datetime import datetime, timezone from shortfx.fxDate.date_convertions import datetime_to_timestamp dt_utc = datetime(2026, 1, 3, 0, 0, 0, tzinfo=timezone.utc) datetime_to_timestamp(dt_utc) 1735862400.0
Cost: O(1)
Source code in shortfx/fxDate/date_convertions.py
decimal_hours_to_time(hours: float) -> time
¶
Converts decimal hours to a time object.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
hours
|
float
|
Decimal hours (e.g. |
required |
Returns:
| Type | Description |
|---|---|
time
|
A |
Raises:
| Type | Description |
|---|---|
TypeError
|
If hours is not numeric. |
ValueError
|
If hours is outside [0, 24). |
Example
decimal_hours_to_time(1.5) datetime.time(1, 30)
Complexity: O(1)
Source code in shortfx/fxDate/date_convertions.py
excel_serial_to_date(serial: Union[int, float]) -> date
¶
Converts an Excel serial date number to a Python date.
Description
Excel uses a serial number system where 1 = 1900-01-01. This function accounts for the Lotus 1-2-3 leap year bug where serial 60 = 1900-02-29 (a non-existent date) — values above 60 are shifted by one day.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
serial
|
Union[int, float]
|
Excel serial date number (≥ 1). |
required |
Returns:
| Type | Description |
|---|---|
date
|
Corresponding |
Raises:
| Type | Description |
|---|---|
TypeError
|
If serial is not numeric. |
ValueError
|
If serial < 1 or equals 60 (the bug date). |
Usage Example
excel_serial_to_date(44927) datetime.date(2023, 1, 1)
Complexity: O(1)
Source code in shortfx/fxDate/date_convertions.py
filetime_to_datetime(filetime: int) -> Tuple[datetime, str]
¶
Converts a Windows FILETIME value to a datetime object and its string representation.
Problem/User Need: Windows systems store timestamps in FILETIME format (100-nanosecond intervals since January 1, 1601 UTC). These need to be converted to standard datetime objects for processing.
Product Goals: Provide accurate conversion of Windows FILETIME values while handling both pre-Unix epoch (before 1970) and modern dates correctly.
Description: This function converts a 64-bit integer representing Windows FILETIME (number of 100-nanosecond intervals since January 1, 1601 UTC) to: 1. A timezone-aware datetime object 2. Its ISO format string representation
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
filetime
|
int
|
The Windows FILETIME value to convert. Must be a positive integer. |
required |
Returns:
| Type | Description |
|---|---|
Tuple[datetime, str]
|
Tuple[datetime, str]: A tuple containing: - datetime: The converted datetime object (UTC) - str: The ISO formatted string representation |
Raises:
| Type | Description |
|---|---|
TypeError
|
If filetime is not an integer |
ValueError
|
If filetime is negative |
Example
Modern date (post-1970)¶
dt, dt_str = filetime_to_datetime(132723834123456789) print(dt) 2022-01-15 12:30:12.345678+00:00 print(dt_str) 2022-01-15 12:30:12.345678
Historical date (pre-1970)¶
dt, dt_str = filetime_to_datetime(130611456000000000) print(dt) 1601-01-01 00:00:00+00:00 print(dt_str) 1601-01-01 00:00:00.000000
Source code in shortfx/fxDate/date_convertions.py
from_iso_to_local_datetime(iso_string: str) -> datetime
¶
Converts an ISO 8601 formatted string to a datetime object in the local timezone.
This function is designed to handle ISO 8601 strings that may or may not contain timezone information (e.g., 'Z' for UTC or a '+HH:MM' offset). It will parse the string and then convert the resulting datetime object to the system's local timezone.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
iso_string
|
str
|
The date and time as an ISO 8601 formatted string. Examples: - '2023-10-26T15:30:45.123456' (naive, assumed local or UTC) - '2023-10-26T15:30:45Z' (UTC) - '2023-10-26T15:30:45+02:00' (UTC+2 offset) |
required |
Returns:
| Name | Type | Description |
|---|---|---|
datetime |
datetime
|
A timezone-aware datetime object representing the input date and time, adjusted to the system's local timezone. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If |
ValueError
|
If |
Example
from datetime import datetime, timezone, timedelta
Example 1: ISO string with UTC 'Z' (Zulu time)¶
iso_utc_string = "2023-10-26T15:30:00Z" local_dt = from_iso_to_local_datetime(iso_utc_string) print(f"UTC string '{iso_utc_string}' -> Local: {local_dt}")
On a system in CEST (UTC+2), this would show: 2023-10-26 17:30:00+02:00¶
Example 2: ISO string with an explicit offset (+02:00)¶
iso_offset_string = "2023-10-26T15:30:00+02:00" local_dt = from_iso_to_local_datetime(iso_offset_string) print(f"Offset string '{iso_offset_string}' -> Local: {local_dt}")
On a system in CEST (UTC+2), this would show: 2023-10-26 15:30:00+02:00¶
Example 3: ISO string without timezone info (naive)¶
datetime.fromisoformat() treats naive strings as local by default,¶
but it's safer to make it aware first for consistent conversion.¶
iso_naive_string = "2023-10-26T15:30:00" local_dt = from_iso_to_local_datetime(iso_naive_string) print(f"Naive string '{iso_naive_string}' -> Local: {local_dt}")
On a system in CEST (UTC+2), this would show: 2023-10-26 15:30:00+02:00¶
Cost: O(1)
Source code in shortfx/fxDate/date_convertions.py
297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 | |
hms_to_seconds(hms: str) -> int
¶
Parses an H:MM:SS or M:SS string to total seconds.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
hms
|
str
|
Duration string (e.g. |
required |
Returns:
| Type | Description |
|---|---|
int
|
Total seconds as an integer. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If hms is not a string. |
ValueError
|
If the format cannot be parsed. |
Example
hms_to_seconds("1:01:01") 3661 hms_to_seconds("5:30") 330
Complexity: O(1)
Source code in shortfx/fxDate/date_convertions.py
integer_to_datetime(yyyymmdd: int) -> datetime
¶
Converts a YYYYMMDD integer back to a datetime object.
Description
Inverse of datetime_to_integer. Parses an integer in YYYYMMDD
format and returns the corresponding datetime at midnight.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
yyyymmdd
|
int
|
Date encoded as integer (e.g. 20260103 → 2026-01-03). |
required |
Returns:
| Name | Type | Description |
|---|---|---|
datetime |
datetime
|
The parsed date at 00:00:00. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If yyyymmdd is not an integer. |
ValueError
|
If the integer does not represent a valid date. |
Example
integer_to_datetime(20260103) datetime.datetime(2026, 1, 3, 0, 0) integer_to_datetime(20240229) datetime.datetime(2024, 2, 29, 0, 0)
Complexity: O(1)
Source code in shortfx/fxDate/date_convertions.py
iso8601_to_datetime(text: str) -> Union[date, datetime]
¶
Parses an ISO 8601 string to a date or datetime object.
Description
Supports YYYY-MM-DD (returns date) and
YYYY-MM-DDTHH:MM:SS[±HH:MM] (returns datetime).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
text
|
str
|
The ISO 8601 string. |
required |
Returns:
| Type | Description |
|---|---|
Union[date, datetime]
|
A |
Raises:
| Type | Description |
|---|---|
TypeError
|
If text is not a string. |
ValueError
|
If text cannot be parsed. |
Usage Example
iso8601_to_datetime("2024-03-15") datetime.date(2024, 3, 15)
Complexity: O(1)
Source code in shortfx/fxDate/date_convertions.py
iso_week_date_to_date(text: str) -> date
¶
Parse an ISO 8601 week date string to a date object.
Description
Accepts strings in YYYY-Www-D format and returns the
corresponding date.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
text
|
str
|
The ISO week date string (e.g. |
required |
Returns:
| Type | Description |
|---|---|
date
|
A |
Raises:
| Type | Description |
|---|---|
TypeError
|
If text is not a string. |
ValueError
|
If text does not match the expected format or contains invalid week/day numbers. |
Usage Example
iso_week_date_to_date("2023-W01-1") datetime.date(2023, 1, 2)
Complexity: O(1)
Source code in shortfx/fxDate/date_convertions.py
julian_to_date(julian_date: int, year: int) -> datetime
¶
Convierte una fecha Juliana (día del año) a un objeto datetime estándar.
Problema/Necesidad del Usuario: Cuando se reciben fechas en formato Julian (día del año) desde sistemas externos, es necesario convertirlas a un formato de fecha estándar para su manipulación y visualización.
Objetivos del Producto: Proporcionar una forma directa de construir una fecha estándar a partir de su número de día del año, manejando correctamente los años bisiestos.
Descripción: Dada un número de día del año (fecha Juliana, de 1 a 366) y un año,
esta función reconstruye y devuelve el objeto datetime correspondiente.
La fecha devuelta tendrá su componente de tiempo establecido a medianoche (00:00:00).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
julian_date
|
int
|
El número del día del año (1 a 365 o 366). Debe ser un entero positivo. |
required |
year
|
int
|
El año al que pertenece la fecha Juliana. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
datetime |
datetime
|
Un objeto |
Raises:
| Type | Description |
|---|---|
TypeError
|
Si 'julian_date' o 'year' no son enteros. |
ValueError
|
Si 'year' está fuera del rango válido (1-9999), o si 'julian_date' está fuera del rango válido (1 a 365/366 dependiendo del año bisiesto). |
Example
from datetime import datetime
Ejemplo 1: Día 1 del año 2025¶
julian_to_date(1, 2025) datetime.datetime(2025, 1, 1, 0, 0)
Ejemplo 2: Día 32 del año 2025 (Febrero 1)¶
julian_to_date(32, 2025) datetime.datetime(2025, 2, 1, 0, 0)
Ejemplo 3: Día 61 del año 2024 (Marzo 1, año bisiesto)¶
julian_to_date(61, 2024) datetime.datetime(2024, 3, 1, 0, 0) # 31 (Ene) + 29 (Feb 2024) + 1 (Mar) = 61
Ejemplo 4: Día 365 del año 2023 (Diciembre 31, año no bisiesto)¶
julian_to_date(365, 2023) datetime.datetime(2023, 12, 31, 0, 0)
Ejemplo 5: Día 366 del año 2024 (Diciembre 31, año bisiesto)¶
julian_to_date(366, 2024) datetime.datetime(2024, 12, 31, 0, 0)
Día Juliana inválido para un año (levantará ValueError)¶
try: julian_to_date(366, 2023) # 2023 no es bisiesto, solo tiene 365 días except ValueError as e: print(f"Error: {e}")
Expected output: Error: Julian date must be between 1 and 365 for year 2023.¶
Cost: O(1)
Source code in shortfx/fxDate/date_convertions.py
684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 | |
list_available_timezones() -> List[str]
¶
Retrieves and returns a sorted list of all available IANA time zone names.
These names are used by the 'zoneinfo' module (and other timezone libraries) to accurately handle time conversions, daylight saving rules, and historical offsets.
Returns:
| Type | Description |
|---|---|
List[str]
|
List[str]: A sorted list of strings, where each string is a valid IANA time zone name. |
Example
timezones = list_available_timezones()
The exact output depends on your system's timezone data, but will include many.¶
print(timezones[:5]) # Print the first 5 for brevity
Expected output might look like: ['Africa/Abidjan', 'Africa/Accra', 'Africa/Addis_Ababa', 'Africa/Algiers', 'Africa/Asmara']¶
print('Europe/Madrid' in timezones) True
Cost: O(n log n) where n is the number of available timezones
Source code in shortfx/fxDate/date_convertions.py
milliseconds_timestamp_to_datetime(timestamp_ms: int) -> datetime
¶
Convierte un sello de tiempo Unix en milisegundos a un objeto datetime.
Problema/Necesidad del Usuario: La contraparte de la anterior. Poder tomar un sello de tiempo en milisegundos y convertirlo de nuevo a un objeto datetime para su manipulación y visualización.
Objetivos del Producto: Completar el ciclo de conversión con sellos de tiempo de milisegundos, permitiendo el procesamiento bidireccional de datos de alta resolución.
Descripción: Esta función toma un entero que representa un sello de tiempo Unix
en milisegundos y lo convierte en un objeto datetime consciente de la zona horaria,
establecido en UTC.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
timestamp_ms
|
int
|
El sello de tiempo Unix en milisegundos a convertir. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
datetime |
datetime
|
Un objeto |
Raises:
| Type | Description |
|---|---|
TypeError
|
Si 'timestamp_ms' no es un entero. |
ValueError
|
Si el sello de tiempo es negativo, lo que no es válido en el contexto Unix. |
Example
from datetime import datetime, timezone milliseconds_timestamp_to_datetime(1749597491123) datetime.datetime(2025, 6, 11, 1, 58, 11, 123000, tzinfo=datetime.timezone.utc)
Cost: O(1)
Source code in shortfx/fxDate/date_convertions.py
modified_julian_date(d: Union[date, datetime]) -> float
¶
Convert a date to Modified Julian Date (MJD).
MJD = JD − 2400000.5, widely used in satellite tracking and radio astronomy.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
d
|
Union[date, datetime]
|
Date or datetime to convert. |
required |
Returns:
| Type | Description |
|---|---|
float
|
Modified Julian Date as a float. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If d is not a date or datetime. |
Example
modified_julian_date(date(2000, 1, 1)) 51544.0
Complexity: O(1)
Source code in shortfx/fxDate/date_convertions.py
parse_date_flexible(text: str, dayfirst: bool = True) -> Optional[Union[date, datetime]]
¶
Parses a date string by trying multiple common formats.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
text
|
str
|
The date string to parse. |
required |
dayfirst
|
bool
|
When ambiguous, treat the first number as the day. |
True
|
Returns:
| Type | Description |
|---|---|
Optional[Union[date, datetime]]
|
A |
Example
parse_date_flexible("15/01/2026") datetime.datetime(2026, 1, 15, 0, 0) parse_date_flexible("2026-04-04") datetime.datetime(2026, 4, 4, 0, 0)
Complexity: O(f) where f is the number of formats tried.
Source code in shortfx/fxDate/date_convertions.py
rata_die(d: Union[date, datetime]) -> int
¶
Convert a date to Rata Die (absolute day number).
Day 1 in Rata Die = January 1, AD 1 (proleptic Gregorian).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
d
|
Union[date, datetime]
|
Date or datetime to convert. |
required |
Returns:
| Type | Description |
|---|---|
int
|
Rata Die integer. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If d is not a date or datetime. |
Example
rata_die(date(2000, 1, 1)) 730120
Complexity: O(1)
Source code in shortfx/fxDate/date_convertions.py
rfc2822_to_datetime(text: str) -> datetime
¶
Parse an RFC 2822 date string to a datetime object.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
text
|
str
|
RFC 2822 formatted date string. |
required |
Returns:
| Type | Description |
|---|---|
datetime
|
Timezone-aware datetime. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the string cannot be parsed. |
Example
rfc2822_to_datetime('Sun, 15 Jun 2025 14:30:00 +0000') datetime.datetime(2025, 6, 15, 14, 30, tzinfo=datetime.timezone.utc)
Complexity: O(1)
Source code in shortfx/fxDate/date_convertions.py
seconds_to_hms(seconds: int) -> str
¶
Converts total seconds to an H:MM:SS string.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
seconds
|
int
|
Non-negative integer of seconds. |
required |
Returns:
| Type | Description |
|---|---|
str
|
Formatted string like |
Raises:
| Type | Description |
|---|---|
TypeError
|
If seconds is not an integer. |
ValueError
|
If seconds is negative. |
Example
seconds_to_hms(3661) '1:01:01'
Complexity: O(1)
Source code in shortfx/fxDate/date_convertions.py
time_to_day_fraction(time_text: str) -> float
¶
Convert a time string to a day fraction (0.0 – 1.0).
Parses a time in "HH:MM:SS" or "HH:MM" format and returns the
proportion of a 24-hour day it represents. Equivalent to the Excel
TIMEVALUE function.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
time_text
|
str
|
Time string in |
required |
Returns:
| Type | Description |
|---|---|
float
|
Float between 0.0 (inclusive) and 1.0 (exclusive). |
Raises:
| Type | Description |
|---|---|
ValueError
|
If time_text cannot be parsed. |
Example
time_to_day_fraction("12:00:00") 0.5 time_to_day_fraction("06:00") 0.25
Complexity: O(1)
Source code in shortfx/fxDate/date_convertions.py
time_to_decimal_hours(t: time) -> float
¶
Converts a time object to decimal hours.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
t
|
time
|
A |
required |
Returns:
| Type | Description |
|---|---|
float
|
Hours as a float (e.g. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If t is not a |
Example
from datetime import time time_to_decimal_hours(time(1, 30)) 1.5
Complexity: O(1)
Source code in shortfx/fxDate/date_convertions.py
time_zone_offset(tz_name: str, dt_val: Union[datetime, None] = None) -> str
¶
Returns the UTC offset string for a timezone at a given datetime.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tz_name
|
str
|
IANA timezone name (e.g. |
required |
dt_val
|
Union[datetime, None]
|
Reference datetime (defaults to now in UTC). |
None
|
Returns:
| Type | Description |
|---|---|
str
|
UTC offset string like |
Raises:
| Type | Description |
|---|---|
TypeError
|
If tz_name is not a string. |
ValueError
|
If tz_name is not a valid timezone. |
Example
time_zone_offset("Europe/Madrid", datetime(2026, 7, 1)) '+02:00'
Complexity: O(1)
Source code in shortfx/fxDate/date_convertions.py
timestamp_to_datetime(timestamp_input: Union[int, float]) -> datetime
¶
Converts a Unix timestamp back to a datetime object.
Description
Converts a Unix timestamp (seconds since epoch: January 1, 1970, 00:00:00 UTC) to a timezone-aware datetime object in UTC. Complements datetime_to_timestamp().
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
timestamp_input
|
Union[int, float]
|
The Unix timestamp to convert. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
datetime |
datetime
|
A timezone-aware datetime object in UTC. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If 'timestamp_input' is not an integer or float. |
ValueError
|
If timestamp is outside valid range for datetime conversion. |
Usage Example
from shortfx.fxDate.date_convertions import timestamp_to_datetime timestamp_to_datetime(1735862400.0) datetime.datetime(2026, 1, 3, 0, 0, tzinfo=datetime.timezone.utc) timestamp_to_datetime(1735862400) datetime.datetime(2026, 1, 3, 0, 0, tzinfo=datetime.timezone.utc)
Cost: O(1)
Source code in shortfx/fxDate/date_convertions.py
unix_epoch_day(d: Union[date, datetime]) -> int
¶
Returns the ordinal day number since the Unix epoch (1970-01-01 = day 0).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
d
|
Union[date, datetime]
|
A date or datetime object. |
required |
Returns:
| Type | Description |
|---|---|
int
|
Integer day count since 1970-01-01. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If d is not a date or datetime. |
Example
from datetime import date unix_epoch_day(date(1970, 1, 1)) 0 unix_epoch_day(date(2026, 4, 8)) 20552
Complexity: O(1)
Source code in shortfx/fxDate/date_convertions.py
unix_epoch_days(d: Union[date, datetime]) -> int
¶
Days elapsed since the Unix epoch (1970-01-01).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
d
|
Union[date, datetime]
|
Date or datetime to convert. |
required |
Returns:
| Type | Description |
|---|---|
int
|
Number of days (negative for dates before 1970-01-01). |
Raises:
| Type | Description |
|---|---|
TypeError
|
If d is not a date or datetime. |
Example
unix_epoch_days(date(2000, 1, 1)) 10957
Complexity: O(1)
Source code in shortfx/fxDate/date_convertions.py
unix_timestamp_to_datetime(timestamp: Union[int, float], tz_info: Optional[str] = None) -> datetime
¶
Converts a UNIX timestamp (seconds since the Epoch) to a datetime object.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
timestamp
|
Union[int, float]
|
The UNIX timestamp. |
required |
tz_info
|
Optional[str]
|
An IANA timezone string (e.g., 'America/New_York', 'Europe/Madrid'). If provided, the resulting datetime will be "aware" (with timezone). If None, the datetime will be "naive" (without timezone, assuming local). |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
datetime |
datetime
|
The resulting datetime object. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If 'timestamp' is not an int or float, or if 'tz_info' is not a string. |
ZoneInfoNotFoundError
|
If the 'tz_info' string doesn't correspond to a valid timezone. |
Example
from datetime import datetime
Convert a timestamp to UTC datetime¶
unix_timestamp_to_datetime(1718092025.0, tz_info='UTC') datetime.datetime(2025, 6, 11, 10, 27, 5, tzinfo=datetime.timezone.utc)
Convert to datetime in Madrid timezone¶
madrid_dt = unix_timestamp_to_datetime(1718092025.0, tz_info='Europe/Madrid') madrid_dt # Note the +02:00 offset for CEST datetime.datetime(2025, 6, 11, 12, 27, 5, tzinfo=zoneinfo.ZoneInfo(key='Europe/Madrid'))
Convert to naive datetime (local time)¶
unix_timestamp_to_datetime(1718092025.0) datetime.datetime(2025, 6, 11, 12, 27, 5) # Output assumes local timezone is CEST+2 for this example
Cost: O(1), direct conversion from timestamp to datetime.
Source code in shortfx/fxDate/date_convertions.py
utc_to_datetime(date_input: Union[datetime, str], input_format: Optional[str] = None, input_tz: Optional[str] = None) -> datetime
¶
Converts any datetime object (aware or naive) or date string to its equivalent UTC representation.
Problem/User Need: The best practice for storing dates is in UTC to avoid timezone and daylight saving issues. Users need a simple way to normalize any date to UTC before saving or processing it.
Product Goals: Promote consistency in date storage and processing, simplifying business logic and preventing timezone-related errors.
Description: Given a date input, this function performs the following:
1. If date_input is a string, it parses it into a datetime object.
2. If the resulting datetime object is naive (has no timezone info):
a. If input_tz is provided, it assumes the naive datetime is in that timezone.
b. If input_tz is NOT provided, it assumes the naive datetime is in the
system's local timezone.
3. If the resulting datetime object is already timezone-aware, it uses its
existing timezone information.
4. Finally, it converts the datetime object to UTC.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
date_input
|
Union[datetime, str]
|
The date to convert to UTC.
Can be a datetime object (e.g., |
required |
input_format
|
Optional[str]
|
The format code string for |
None
|
input_tz
|
Optional[str]
|
The IANA timezone name of the |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
datetime |
datetime
|
A timezone-aware datetime object representing the input date and time in UTC. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If |
ValueError
|
If |
Example
from datetime import datetime, timezone import zoneinfo
Scenario 1: Input is a naive datetime object (system local time is CEST = UTC+2)¶
Assuming the system's local timezone is Europe/Madrid (currently CEST, UTC+2)¶
naive_dt_local = datetime(2025, 6, 11, 10, 0, 0) # 10:00 AM local time utc_dt = utc_to_datetime(naive_dt_local) print(f"Naive local (10:00 CEST) -> UTC: {utc_dt}")
Expected: 2025-06-11 08:00:00+00:00 (10:00 CEST - 2 hours = 08:00 UTC)¶
Scenario 2: Input is an aware datetime object (e.g., in 'America/Los_Angeles')¶
la_tz = zoneinfo.ZoneInfo('America/Los_Angeles') aware_dt_la = datetime(2025, 6, 11, 10, 0, 0, tzinfo=la_tz) # 10:00 AM in LA (PDT, UTC-7) utc_dt = utc_to_datetime(aware_dt_la) print(f"Aware LA (10:00 PDT) -> UTC: {utc_dt}")
Expected: 2025-06-11 17:00:00+00:00 (10:00 PDT + 7 hours = 17:00 UTC)¶
Scenario 3: Input is a string, and we specify its original timezone¶
Date string "2025-06-11 10:00:00" is in 'Asia/Tokyo' (JST, UTC+9)¶
utc_dt = utc_to_datetime("2025-06-11 10:00:00", "%Y-%m-%d %H:%M:%S", "Asia/Tokyo") print(f"String Tokyo (10:00 JST) -> UTC: {utc_dt}")
Expected: 2025-06-11 01:00:00+00:00 (10:00 JST - 9 hours = 01:00 UTC)¶
Scenario 4: Input is a string with no explicit timezone provided, assumes local¶
Assuming local system is CEST (UTC+2)¶
utc_dt = utc_to_datetime("2025-06-11 10:00:00", "%Y-%m-%d %H:%M:%S") print(f"String local (10:00 CEST) -> UTC: {utc_dt}")
Expected: 2025-06-11 08:00:00+00:00¶
Cost: O(1)
Source code in shortfx/fxDate/date_convertions.py
399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 | |
utc_to_midnight_iso(p_datetime: datetime) -> datetime
¶
Convierte un datetime a su equivalente a medianoche UTC.
Problem/User Need: Es común necesitar normalizar fechas a medianoche UTC para comparaciones consistentes o para asegurar que todos los eventos empiecen al inicio del día.
Product Goals: Proporcionar una forma sencilla de normalizar cualquier datetime a medianoche UTC manteniendo la fecha.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
p_datetime
|
datetime
|
El objeto datetime a convertir. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
datetime |
datetime
|
Un nuevo objeto datetime establecido a medianoche UTC (00:00:00) para la fecha dada. |
Raises:
| Type | Description |
|---|---|
TypeError
|
Si p_datetime no es un objeto datetime. |
Example
from datetime import datetime, timezone
Datetime con hora específica¶
dt = datetime(2025, 6, 11, 15, 30, 45, tzinfo=timezone.utc) midnight_dt = utc_to_midnight_iso(dt) print(midnight_dt) 2025-06-11 00:00:00+00:00
Datetime sin zona horaria¶
naive_dt = datetime(2025, 6, 11, 15, 30, 45) midnight_dt = utc_to_midnight_iso(naive_dt) print(midnight_dt) 2025-06-11 00:00:00+00:00
Cost: O(1)
Source code in shortfx/fxDate/date_convertions.py
utc_to_timezone(input_datetime: datetime, target_tz_name: str = 'Europe/Madrid') -> datetime
¶
Localizes a naive datetime object to the target timezone or validates an aware datetime, then returns it localized to the target timezone.
This function is used when you have a datetime that might be naive (without tzinfo)
and you need to assume a specific timezone for it, or when you have an aware datetime
and want to ensure it's converted to the target timezone. If the input datetime is naive,
it will be localized directly to the `target_tz_name`. If it's already timezone-aware,
it will be converted to the `target_tz_name`.
Args:
input_datetime (datetime): The datetime object to process. If it's naive,
it will be localized to `target_tz_name`. If it's
already timezone-aware, it will be converted
to `target_tz_name`.
target_tz_name (str): The name of the target timezone to localize/convert to (e.g.,
'America/New_York', 'Europe/Madrid', 'Asia/Tokyo').
These are typically IANA timezone database names.
Returns:
datetime: A new timezone-aware datetime object representing the same moment in time,
but localized to the `target_tz_name`.
Raises:
TypeError: If `input_datetime` is not a datetime object.
zoneinfo.ZoneInfoNotFoundError: If `target_tz_name` is not a recognized timezone
in the system's timezone database.
Example:
>>> from datetime import datetime, timezone
>>> import zoneinfo
>>> # 1. Define a target timezone (e.g., Europe/Madrid)
>>> madrid_tz = zoneinfo.ZoneInfo('Europe/Madrid')
>>> # 2. Define a naive datetime
>>> naive_dt = datetime(2025, 6, 11, 10, 0, 0) # 10:00 AM, but in which timezone?
>>> print(f"Original Naive: {naive_dt}")
>>> # Localize naive_dt directly to Madrid time (assumes 10:00 AM Madrid time)
>>> localized_to_madrid = utc_to_timezone(naive_dt, 'Europe/Madrid')
>>> print(f"Localized to Madrid: {localized_to_madrid}")
# Expected: 2025-06-11 10:00:00+02:00 (since June in Madrid is UTC+2)
>>> # Now convert the Madrid-localized time to New York time (PDT = UTC-4 in June for NY)
>>> madrid_to_ny = utc_to_timezone(localized_to_madrid, 'America/New_York')
>>> print(f"Madrid time converted to New York: {madrid_to_ny}")
# Expected: 2025-06-11 04:00:00-04:00 (10:00 Madrid is 08:00 UTC, which is 04:00 NY)
>>> # 3. Define an already aware datetime (e.g., in UTC)
>>> utc_aware_dt = datetime(2025, 6, 11, 8, 0, 0, tzinfo=timezone.utc) # 8:00 AM UTC
>>> print(f"
Original UTC Aware: {utc_aware_dt}")
>>> # Convert the UTC aware datetime to Madrid time
>>> utc_to_madrid = utc_to_timezone(utc_aware_dt, 'Europe/Madrid')
>>> print(f"UTC Aware converted to Madrid: {utc_to_madrid}")
# Expected: 2025-06-11 10:00:00+02:00
Cost: O(1)
Source code in shortfx/fxDate/date_convertions.py
524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 | |