🔍 Code Extractor

function load_email_dates

Maturity: 46

Reads a CSV file (DOWNLOAD_REGISTER) containing email metadata and extracts filename-to-date mappings, parsing dates in YYYY-MM-DD format.

File:
/tf/active/vicechatdev/mailsearch/copy_signed_documents.py
Lines:
94 - 107
Complexity:
simple

Purpose

This function loads email received dates from a CSV download register file and creates a dictionary mapping filenames to their corresponding datetime objects. It's designed to track when email attachments or files were downloaded/received, handling parsing errors gracefully by skipping invalid entries. The function is useful for file management systems that need to maintain temporal metadata about downloaded email content.

Source Code

def load_email_dates():
    """Load file dates from download register"""
    email_dates = {}
    with open(DOWNLOAD_REGISTER, 'r', encoding='utf-8') as f:
        reader = csv.DictReader(f)
        for row in reader:
            filename = row['filename']
            date_str = row['received_date']
            try:
                date_obj = datetime.strptime(date_str.split()[0], '%Y-%m-%d')
                email_dates[filename] = date_obj
            except Exception:
                pass
    return email_dates

Return Value

Returns a dictionary (dict) where keys are filenames (str) from the CSV's 'filename' column and values are datetime objects representing the received dates. Only successfully parsed dates are included; rows with invalid dates are silently skipped. Returns an empty dictionary if the file doesn't exist or has no valid entries.

Dependencies

  • csv
  • datetime

Required Imports

import csv
from datetime import datetime

Usage Example

# Define the download register path
DOWNLOAD_REGISTER = 'email_downloads.csv'

# CSV file content example:
# filename,received_date
# report.pdf,2024-01-15 10:30:00
# invoice.xlsx,2024-01-16

import csv
from datetime import datetime

def load_email_dates():
    email_dates = {}
    with open(DOWNLOAD_REGISTER, 'r', encoding='utf-8') as f:
        reader = csv.DictReader(f)
        for row in reader:
            filename = row['filename']
            date_str = row['received_date']
            try:
                date_obj = datetime.strptime(date_str.split()[0], '%Y-%m-%d')
                email_dates[filename] = date_obj
            except Exception:
                pass
    return email_dates

# Usage
dates = load_email_dates()
for filename, date in dates.items():
    print(f"{filename}: {date.strftime('%Y-%m-%d')}")

Best Practices

  • Ensure DOWNLOAD_REGISTER constant is defined before calling this function
  • The function silently ignores parsing errors; consider logging failures for debugging in production
  • The CSV file must have 'filename' and 'received_date' columns or KeyError will be raised
  • Date strings can include time information after the date, but only the date portion (YYYY-MM-DD) is parsed
  • Consider adding file existence checks before calling to provide better error messages
  • The function will raise FileNotFoundError if DOWNLOAD_REGISTER path doesn't exist
  • UTF-8 encoding is assumed; files with different encodings may cause UnicodeDecodeError
  • For large CSV files, consider implementing pagination or streaming to reduce memory usage

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function get_email_templates 52.8% similar

    Loads HTML email templates from a predefined directory structure and returns them as a dictionary mapping template names to their content.

    From: /tf/active/vicechatdev/CDocs/utils/notifications.py
  • function load_data 50.2% similar

    Loads a CSV dataset from a specified filepath using pandas, with fallback to creating sample data if the file is not found.

    From: /tf/active/vicechatdev/vice_ai/smartstat_scripts/5a059cb7-3903-4020-8519-14198d1f39c9/analysis_1.py
  • function copy_file_with_date 49.9% similar

    Copies a file from source to destination and sets the file's modification and access times to match a provided datetime object.

    From: /tf/active/vicechatdev/mailsearch/copy_signed_documents.py
  • function load_dataset 49.3% similar

    Loads a CSV dataset from a specified file path using pandas and returns it as a DataFrame with error handling for file not found and general exceptions.

    From: /tf/active/vicechatdev/vice_ai/smartstat_scripts/e1ecec5f-4ea5-49c5-b4f5-d051ce851294/project_1/analysis.py
  • function fix_file_dates 49.2% similar

    Normalizes all timestamp attributes (creation, modification, access) of a file to the oldest timestamp among them, with optional dry-run mode for preview.

    From: /tf/active/vicechatdev/mailsearch/fix_file_dates.py
← Back to Browse