Skip to main content

Overview

The fmt_fecha() function provides robust date formatting for invoice processing, converting various date input formats into a standardized string format. It handles invalid dates gracefully and uses day-first parsing to accommodate Latin American date conventions.

Function Signature

def fmt_fecha(valor, formato="%d/%m/%Y")
Source: main.py:25-34

Parameters

valor
any
required
The date value to format. Can be:
  • String date representation (e.g., “15/03/2026”, “2026-03-15”)
  • Pandas datetime object
  • Python datetime object
  • Empty string or NaN value
formato
string
default:"%d/%m/%Y"
The output date format using Python strftime codes. Common formats:
  • "%d/%m/%Y" → “15/03/2026” (default)
  • "%Y-%m-%d" → “2026-03-15”
  • "%d-%m-%Y" → “15-03-2026”
  • "%B %d, %Y" → “March 15, 2026”

Return Value

result
string | None
Returns the formatted date string according to the specified format. Returns None if the input is empty or NaN. Returns the original valor unchanged if parsing fails.

Date Parsing Behavior

The function uses dayfirst=True when parsing dates with pd.to_datetime(). This means ambiguous dates like “03/04/2026” are interpreted as April 3rd, 2026 (not March 4th), following Latin American date conventions.

Parsing Logic

  1. Empty/NaN Check: If valor is NaN or empty string, returns None immediately
  2. Date Parsing: Attempts to parse using pd.to_datetime() with dayfirst=True and errors="coerce"
  3. Validation: If parsing results in NaT (Not a Time), returns original valor unchanged
  4. Formatting: If successful, formats the datetime using the specified formato
  5. Error Handling: If any exception occurs, returns original valor unchanged

Error Handling

The function includes multiple layers of error protection:

Null/Empty Values

Returns None for NaN or empty strings without attempting parsing

Invalid Dates

Returns original value if date cannot be parsed (e.g., “invalid-date”)

Exception Safety

Catches all exceptions and returns original value to prevent crashes

Coerce Errors

Uses errors="coerce" to convert unparseable dates to NaT gracefully

Examples

Basic Usage

# Standard date formatting (day/month/year)
fmt_fecha("15/03/2026")
# Returns: "15/03/2026"

# ISO format input
fmt_fecha("2026-03-15")
# Returns: "15/03/2026"

# Custom output format
fmt_fecha("2026-03-15", formato="%Y-%m-%d")
# Returns: "2026-03-15"

Day-First Parsing

# Ambiguous date: interpreted as day/month/year
fmt_fecha("03/04/2026")
# Returns: "03/04/2026" (April 3rd, not March 4th)

# Unambiguous date
fmt_fecha("25/12/2025")
# Returns: "25/12/2025" (December 25th)

Error Handling

# Empty or NaN values
fmt_fecha("")
# Returns: None

fmt_fecha(pd.NA)
# Returns: None

# Invalid date string
fmt_fecha("not-a-date")
# Returns: "not-a-date" (unchanged)

# Partially valid date
fmt_fecha("32/13/2026")  # Invalid day and month
# Returns: "32/13/2026" (unchanged)

Invoice Processing Context

# As used in the invoice transformation pipeline (main.py:75-77)
fecha_emision = fmt_fecha(row["Fecha Emision"])
# Converts Excel date to "dd/mm/yyyy" format

fecha_vencimiento = fmt_fecha(row["Fecha Vencimiento"])
# Formats due date

fecha_pago = fmt_fecha(row["Fecha Pago"], "%d/%m/%Y")
# Formats payment date with explicit format

Common Use Cases

Input TypeExample InputOutput (Default)Notes
String (DMY)“15/03/2026""15/03/2026”Direct passthrough if already formatted
String (ISO)“2026-03-15""15/03/2026”Converted to day-first format
Pandas Timestamppd.Timestamp("2026-03-15")”15/03/2026”Formatted from datetime object
Excel Serial46095”15/03/2026”Pandas auto-converts Excel date serials
Empty/NaN"" or pd.NANoneNull-safe handling
Invalid”invalid""invalid”Returns original value
When working with dates from Excel files, be aware that Excel may store dates as serial numbers. Pandas read_excel() automatically converts these to datetime objects, which fmt_fecha() can then format correctly.

Technical Details

Dependencies

  • pandas: For robust date parsing with pd.to_datetime() and null handling with pd.isna()
  • datetime: For strftime formatting codes

Performance Considerations

  • The function uses errors="coerce" which is safer but slightly slower than errors="raise"
  • For bulk processing of thousands of dates, consider vectorizing with pandas Series operations instead of row-by-row calls

Integration Points

This utility is called from:
  • transformar_fila() function (main.py:74) - Used to format invoice dates before JSON transformation
  • Invoice document emission dates: IdentificacionDocumento.FechaEmision
  • Payment due dates: IdentificacionDocumento.FechaVencimiento
  • Payment dates: FormasPago[].Fecha

Build docs developers (and LLMs) love