Web Date & Time Python Samples

Web Python date and time examples including getting current time, formatting, parsing, and timezone operations

Key Facts

Category
Python
Items
3
Format Families
text

Sample Overview

Web Python date and time examples including getting current time, formatting, parsing, and timezone operations This sample set belongs to Python and can be used to test related workflows inside Elysia Tools.

💻 Get Current Time python

🟢 simple ⭐⭐

Get current system time and date using datetime and time modules with various precision levels

⏱️ 20 min 🏷️ python, web, datetime, time
Prerequisites: Basic Python, datetime module
# Web Python Get Current Time Examples
# Getting current system time and date with various precision

# 1. Basic Current Time
from datetime import datetime, date, time, timezone
from time import time as time_time, time_ns, ctime, localtime, gmtime, strftime
import time

def get_current_datetime() -> datetime:
    """
    Get current date and time

    Returns:
        Current datetime object
    """
    return datetime.now()

def get_current_date() -> date:
    """
    Get current date only

    Returns:
        Current date object
    """
    return date.today()

def get_current_time() -> time:
    """
    Get current time only

    Returns:
        Current time object
    """
    return datetime.now().time()

def get_current_timestamp() -> float:
    """
    Get current Unix timestamp

    Returns:
        Timestamp as float
    """
    return time.time()

def get_current_timestamp_ns() -> int:
    """
    Get current Unix timestamp in nanoseconds

    Returns:
        Timestamp as integer (nanoseconds)
    """
    return time.time_ns()

# 2. Time with Timezone
def get_utc_now() -> datetime:
    """
    Get current UTC time

    Returns:
        Current UTC datetime
    """
    return datetime.now(timezone.utc)

def get_current_timezone() -> datetime:
    """
    Get current time with local timezone

    Returns:
        Current datetime with local timezone
    """
    return datetime.now().astimezone()

def get_timezone_offset() -> int:
    """
    Get local timezone offset in seconds

    Returns:
        Offset in seconds
    """
    return time.timezone if time.daylight == 0 else time.altzone

def get_timezone_name() -> str:
    """
    Get local timezone name

    Returns:
        Timezone name
    """
    return time.tzname[time.daylight]

# 3. High Precision Time
def get_high_precision_time() -> float:
    """
    Get time with high precision

    Returns:
        Time as float (seconds since epoch)
    """
    return time_time()

def get_monotonic_time() -> float:
    """
    Get monotonic time (cannot go backwards)

    Returns:
        Monotonic clock time
    """
    return time.monotonic()

def get_perf_counter() -> float:
    """
    Get performance counter time (highest resolution)

    Returns:
        Performance counter time
    """
    return time.perf_counter()

def get_process_time() -> float:
    """
    Get process CPU time

    Returns:
        Process CPU time
    """
    return time.process_time()

def get_thread_time() -> float:
    """
    Get thread CPU time

    Returns:
        Thread CPU time
    """
    return time.thread_time()

# 4. Time Components
def get_current_year() -> int:
    """Get current year"""
    return datetime.now().year

def get_current_month() -> int:
    """Get current month (1-12)"""
    return datetime.now().month

def get_current_day() -> int:
    """Get current day of month (1-31)"""
    return datetime.now().day

def get_current_hour() -> int:
    """Get current hour (0-23)"""
    return datetime.now().hour

def get_current_minute() -> int:
    """Get current minute (0-59)"""
    return datetime.now().minute

def get_current_second() -> int:
    """Get current second (0-59)"""
    return datetime.now().second

def get_current_microsecond() -> int:
    """Get current microsecond (0-999999)"""
    return datetime.now().microsecond

def get_time_components() -> dict:
    """
    Get all time components as dictionary

    Returns:
        Dictionary with all components
    """
    now = datetime.now()
    return {
        'year': now.year,
        'month': now.month,
        'day': now.day,
        'hour': now.hour,
        'minute': now.minute,
        'second': now.second,
        'microsecond': now.microsecond,
        'weekday': now.weekday(),
        'iso_weekday': now.isoweekday()
    }

# 5. Week and Day Information
def get_current_weekday() -> int:
    """
    Get current weekday (0=Monday, 6=Sunday)

    Returns:
        Weekday number
    """
    return datetime.now().weekday()

def get_current_iso_weekday() -> int:
    """
    Get current ISO weekday (1=Monday, 7=Sunday)

    Returns:
        ISO weekday number
    """
    return datetime.now().isoweekday()

def get_week_of_year() -> int:
    """
    Get current week of year

    Returns:
        Week number (1-53)
    """
    return datetime.now().isocalendar()[1]

def get_day_of_year() -> int:
    """
    Get current day of year

    Returns:
        Day of year (1-366)
    """
    return datetime.now().timetuple().tm_yday

def get_weekday_name() -> str:
    """
    Get current weekday name

    Returns:
        Weekday name (e.g., 'Monday')
    """
    return datetime.now().strftime('%A')

def get_month_name() -> str:
    """
    Get current month name

    Returns:
        Month name (e.g., 'January')
    """
    return datetime.now().strftime('%B')

def get_weekday_name_abbreviated() -> str:
    """
    Get abbreviated weekday name

    Returns:
        Abbreviated weekday name (e.g., 'Mon')
    """
    return datetime.now().strftime('%a')

def get_month_name_abbreviated() -> str:
    """
    Get abbreviated month name

    Returns:
        Abbreviated month name (e.g., 'Jan')
    """
    return datetime.now().strftime('%b')

# 6. Time Strings
def get_time_string() -> str:
    """
    Get current time as string

    Returns:
        Time string (HH:MM:SS)
    """
    return datetime.now().strftime('%H:%M:%S')

def get_date_string() -> str:
    """
    Get current date as string

    Returns:
        Date string (YYYY-MM-DD)
    """
    return datetime.now().strftime('%Y-%m-%d')

def get_datetime_string() -> str:
    """
    Get current datetime as string

    Returns:
        DateTime string (YYYY-MM-DD HH:MM:SS)
    """
    return datetime.now().strftime('%Y-%m-%d %H:%M:%S')

def get_iso_datetime() -> str:
    """
    Get ISO 8601 formatted datetime

    Returns:
        ISO formatted string
    """
    return datetime.now().isoformat()

def get_ctime_string() -> str:
    """
    Get ctime formatted string

    Returns:
        Ctime string
    """
    return ctime()

def get_custom_format(format_string: str) -> str:
    """
    Get time with custom format

    Args:
        format_string: Format string

    Returns:
        Formatted time string
    """
    return datetime.now().strftime(format_string)

# 7. Relative Time
def get_time_since_epoch() -> float:
    """
    Get seconds since Unix epoch

    Returns:
        Seconds since epoch
    """
    return time.time()

def get_time_until_midnight() -> float:
    """
    Get seconds until midnight

    Returns:
        Seconds until midnight
    """
    now = datetime.now()
    midnight = datetime.now().replace(hour=23, minute=59, second=59)
    return (midnight - now).total_seconds()

def get_time_since_midnight() -> float:
    """
    Get seconds since midnight

    Returns:
        Seconds since midnight
    """
    now = datetime.now()
    midnight = now.replace(hour=0, minute=0, second=0, microsecond=0)
    return (now - midnight).total_seconds()

def get_days_in_month() -> int:
    """
    Get number of days in current month

    Returns:
        Days in month
    """
    from calendar import monthrange
    now = datetime.now()
    return monthrange(now.year, now.month)[1]

def is_leap_year() -> bool:
    """
    Check if current year is leap year

    Returns:
        True if leap year
    """
    from calendar import isleap
    return isleap(datetime.now().year)

# 8. Multiple Time Representations
def get_all_time_formats() -> dict:
    """
    Get time in all common formats

    Returns:
        Dictionary with various formats
    """
    now = datetime.now()
    return {
        'iso': now.isoformat(),
        'timestamp': time.time(),
        'ctime': ctime(),
        'date': get_date_string(),
        'time': get_time_string(),
        'datetime': get_datetime_string(),
        'year': now.year,
        'month': now.month,
        'day': now.day,
        'hour': now.hour,
        'minute': now.minute,
        'second': now.second
    }

# 9. Time Measurements
def measure_time_start() -> float:
    """
    Start time measurement

    Returns:
        Start time
    """
    return time.perf_counter()

def measure_time_end(start_time: float) -> float:
    """
    End time measurement

    Args:
        start_time: Start time from measure_time_start

    Returns:
        Elapsed time in seconds
    """
    return time.perf_counter() - start_time

# Usage Examples
def demonstrate_get_current_time():
    print("=== Web Python Get Current Time Examples ===\n")

    # 1. Basic time
    print("--- 1. Basic Current Time ---")
    print(f"Current datetime: {get_current_datetime()}")
    print(f"Current date: {get_current_date()}")
    print(f"Current time: {get_current_time()}")
    print(f"Unix timestamp: {get_current_timestamp()}")
    print(f"Timestamp (ns): {get_current_timestamp_ns()}")

    # 2. Timezone
    print("\n--- 2. Timezone Information ---")
    print(f"UTC now: {get_utc_now()}")
    print(f"Local timezone: {get_current_timezone()}")
    print(f"Timezone offset: {get_timezone_offset()} seconds")
    print(f"Timezone name: {get_timezone_name()}")

    # 3. High precision
    print("\n--- 3. High Precision Time ---")
    print(f"High precision: {get_high_precision_time()}")
    print(f"Monotonic: {get_monotonic_time()}")
    print(f"Perf counter: {get_perf_counter()}")
    print(f"Process time: {get_process_time()}")

    # 4. Components
    print("\n--- 4. Time Components ---")
    print(f"Time components: {get_time_components()}")

    # 5. Week/Day info
    print("\n--- 5. Week and Day Information ---")
    print(f"Weekday (0=Mon): {get_current_weekday()}")
    print(f"ISO weekday (1=Mon): {get_current_iso_weekday()}")
    print(f"Week of year: {get_week_of_year()}")
    print(f"Day of year: {get_day_of_year()}")
    print(f"Weekday name: {get_weekday_name()}")
    print(f"Month name: {get_month_name()}")

    # 6. String formats
    print("\n--- 6. String Formats ---")
    print(f"Time string: {get_time_string()}")
    print(f"Date string: {get_date_string()}")
    print(f"DateTime string: {get_datetime_string()}")
    print(f"ISO format: {get_iso_datetime()}")
    print(f"Custom format: {get_custom_format('%d/%m/%Y %H:%M')}")

    # 7. Relative time
    print("\n--- 7. Relative Time ---")
    print(f"Until midnight: {get_time_until_midnight():.0f} seconds")
    print(f"Since midnight: {get_time_since_midnight():.0f} seconds")
    print(f"Days in month: {get_days_in_month()}")
    print(f"Is leap year: {is_leap_year()}")

    # 8. All formats
    print("\n--- 8. All Formats ---")
    all_formats = get_all_time_formats()
    for key, value in all_formats.items():
        print(f"{key}: {value}")

    # 9. Time measurement
    print("\n--- 9. Time Measurement ---")
    start = measure_time_start()
    time.sleep(0.1)  # Simulate work
    elapsed = measure_time_end(start)
    print(f"Elapsed time: {elapsed:.3f} seconds")

    print("\n=== All Get Current Time Examples Completed ===")

# Export functions
# export { get_current_datetime, get_current_date, get_current_time }
# export { get_current_timestamp, get_current_timestamp_ns }
# export { get_utc_now, get_current_timezone, get_timezone_offset, get_timezone_name }
# export { get_high_precision_time, get_monotonic_time, get_perf_counter }
# export { get_process_time, get_thread_time }
# export { get_current_year, get_current_month, get_current_day }
# export { get_current_hour, get_current_minute, get_current_second, get_current_microsecond }
# export { get_time_components }
# export { get_current_weekday, get_current_iso_weekday, get_week_of_year, get_day_of_year }
# export { get_weekday_name, get_month_name, get_weekday_name_abbreviated, get_month_name_abbreviated }
# export { get_time_string, get_date_string, get_datetime_string, get_iso_datetime }
# export { get_ctime_string, get_custom_format }
# export { get_time_since_epoch, get_time_until_midnight, get_time_since_midnight }
# export { get_days_in_month, is_leap_year }
# export { get_all_time_formats }
# export { measure_time_start, measure_time_end }
# export { demonstrate_get_current_time }

💻 Time Formatting python

🟡 intermediate ⭐⭐⭐

Format datetime objects to strings using various format codes and custom patterns

⏱️ 25 min 🏷️ python, web, datetime, formatting
Prerequisites: Intermediate Python, datetime module, strftime
# Web Python Time Formatting Examples
# Converting datetime objects to formatted strings

# 1. Standard Format Codes
from datetime import datetime, date, time
from typing import Optional

def format_year(dt: datetime) -> str:
    """Format year (YYYY or YY)"""
    return {
        'full': dt.strftime('%Y'),
        'short': dt.strftime('%y'),
        'iso': dt.isoformat()
    }

def format_month(dt: datetime) -> dict:
    """
    Format month in various ways

    Args:
        dt: Datetime object

    Returns:
        Dictionary with various formats
    """
    return {
        'numeric': dt.strftime('%m'),
        'numeric_zero': dt.strftime('%-m'),
        'name': dt.strftime('%B'),
        'name_abbrev': dt.strftime('%b')
    }

def format_day(dt: datetime) -> dict:
    """
    Format day in various ways

    Args:
        dt: Datetime object

    Returns:
        Dictionary with various formats
    """
    return {
        'numeric': dt.strftime('%d'),
        'numeric_space': dt.strftime('%e'),
        'with_ordinal': str(dt.day) + ('th' if 11 <= dt.day <= 13 else {1:'st', 2:'nd', 3:'rd'}.get(dt.day % 10, 'th')),
        'name': dt.strftime('%A'),
        'name_abbrev': dt.strftime('%a')
    }

def format_time(dt: datetime) -> dict:
    """
    Format time in various ways

    Args:
        dt: Datetime object

    Returns:
        Dictionary with various formats
    """
    return {
        '24h': dt.strftime('%H:%M:%S'),
        '12h': dt.strftime('%I:%M:%S %p'),
        '24h_short': dt.strftime('%H:%M'),
        '12h_short': dt.strftime('%I:%M %p'),
        'hour_24': dt.strftime('%H'),
        'hour_12': dt.strftime('%I'),
        'minute': dt.strftime('%M'),
        'second': dt.strftime('%S'),
        'period': dt.strftime('%p')
    }

# 2. Common Date Formats
def format_iso8601(dt: datetime) -> str:
    """
    Format as ISO 8601

    Args:
        dt: Datetime object

    Returns:
        ISO 8601 string
    """
    return dt.isoformat()

def format_rfc2822(dt: datetime) -> str:
    """
    Format as RFC 2822 (email format)

    Args:
        dt: Datetime object

    Returns:
        RFC 2822 string
    """
    return dt.strftime('%a, %d %b %Y %H:%M:%S %z')

def format_rfc3339(dt: datetime) -> str:
    """
    Format as RFC 3339

    Args:
        dt: Datetime object

    Returns:
        RFC 3339 string
    """
    return dt.strftime('%Y-%m-%dT%H:%M:%S%z')

def format_http_date(dt: datetime) -> str:
    """
    Format as HTTP date

    Args:
        dt: Datetime object

    Returns:
        HTTP date string
    """
    return dt.strftime('%a, %d %b %Y %H:%M:%S GMT')

# 3. Regional Formats
def format_us_date(dt: datetime) -> str:
    """
    Format as US date (MM/DD/YYYY)

    Args:
        dt: Datetime object

    Returns:
        US format date
    """
    return dt.strftime('%m/%d/%Y')

def format_eu_date(dt: datetime) -> str:
    """
    Format as European date (DD/MM/YYYY)

    Args:
        dt: Datetime object

    Returns:
        European format date
    """
    return dt.strftime('%d/%m/%Y')

def format_iso_date(dt: datetime) -> str:
    """
    Format as ISO date (YYYY-MM-DD)

    Args:
        dt: Datetime object

    Returns:
        ISO format date
    """
    return dt.strftime('%Y-%m-%d')

def format_chinese_date(dt: datetime) -> str:
    """
    Format as Chinese date (YYYY年MM月DD日)

    Args:
        dt: Datetime object

    Returns:
        Chinese format date
    """
    return dt.strftime('%Y年%m月%d日')

def format_japanese_date(dt: datetime) -> str:
    """
    Format as Japanese date (YYYY年MM月DD日)

    Args:
        dt: Datetime object

    Returns:
        Japanese format date
    """
    return dt.strftime('%Y年%m月%d日')

# 4. Custom Formats
def format_readable(dt: datetime) -> str:
    """
    Format in human-readable form

    Args:
        dt: Datetime object

    Returns:
        Readable string
    """
    return dt.strftime('%A, %B %d, %Y at %I:%M %p')

def format_compact(dt: datetime) -> str:
    """
    Format in compact form

    Args:
        dt: Datetime object

    Returns:
        Compact string
    """
    return dt.strftime('%Y%m%d_%H%M%S')

def format_with_timezone(dt: datetime) -> str:
    """
    Format with timezone info

    Args:
        dt: Datetime object

    Returns:
        String with timezone
    """
    return dt.strftime('%Y-%m-%d %H:%M:%S %Z')

def format_friendly(dt: datetime) -> str:
    """
    Format in friendly form

    Args:
        dt: Datetime object

    Returns:
        Friendly string
    """
    now = datetime.now()
    diff = (now - dt).total_seconds()

    if diff < 60:
        return 'just now'
    elif diff < 3600:
        minutes = int(diff / 60)
        return f'{minutes} minute{"s" if minutes > 1 else ""} ago'
    elif diff < 86400:
        hours = int(diff / 3600)
        return f'{hours} hour{"s" if hours > 1 else ""} ago'
    elif diff < 604800:
        days = int(diff / 86400)
        return f'{days} day{"s" if days > 1 else ""} ago'
    else:
        return dt.strftime('%Y-%m-%d')

# 5. Time Formatting
def format_duration(seconds: float) -> str:
    """
    Format duration in human-readable form

    Args:
        seconds: Duration in seconds

    Returns:
        Formatted duration
    """
    hours = int(seconds // 3600)
    minutes = int((seconds % 3600) // 60)
    secs = int(seconds % 60)

    if hours > 0:
        return f'{hours}h {minutes}m {secs}s'
    elif minutes > 0:
        return f'{minutes}m {secs}s'
    else:
        return f'{secs}s'

def format_duration_precise(seconds: float) -> str:
    """
    Format duration with milliseconds

    Args:
        seconds: Duration in seconds

    Returns:
        Formatted duration with ms
    """
    hours = int(seconds // 3600)
    minutes = int((seconds % 3600) // 60)
    secs = int(seconds % 60)
    millis = int((seconds % 1) * 1000)

    if hours > 0:
        return f'{hours}h {minutes}m {secs}s {millis}ms'
    elif minutes > 0:
        return f'{minutes}m {secs}s {millis}ms'
    else:
        return f'{secs}s {millis}ms'

# 6. Relative Formatting
def format_relative_to_now(dt: datetime) -> str:
    """
    Format datetime relative to now

    Args:
        dt: Datetime object

    Returns:
        Relative time string
    """
    now = datetime.now()
    diff = dt - now if dt > now else now - dt
    seconds = diff.total_seconds()
    future = dt > now

    if seconds < 60:
        amount = int(seconds)
        unit = 'second'
    elif seconds < 3600:
        amount = int(seconds / 60)
        unit = 'minute'
    elif seconds < 86400:
        amount = int(seconds / 3600)
        unit = 'hour'
    elif seconds < 2592000:
        amount = int(seconds / 86400)
        unit = 'day'
    elif seconds < 31536000:
        amount = int(seconds / 2592000)
        unit = 'month'
    else:
        amount = int(seconds / 31536000)
        unit = 'year'

    plural = 's' if amount > 1 else ''
    direction = 'in' if future else 'ago'
    return f'{amount} {unit}{plural} {direction}'

# 7. Business Date Formats
def format_quarter(dt: datetime) -> str:
    """
    Format as quarter

    Args:
        dt: Datetime object

    Returns:
        Quarter string
    """
    quarter = (dt.month - 1) // 3 + 1
    return f'Q{quarter} {dt.year}'

def format_week_number(dt: datetime) -> str:
    """
    Format with week number

    Args:
        dt: Datetime object

    Returns:
        Week string
    """
    return dt.strftime('%Y-W%W')

def format_day_of_year(dt: datetime) -> str:
    """
    Format with day of year

    Args:
        dt: Datetime object

    Returns:
        Day of year string
    """
    return dt.strftime(f'%Y-{dt.timetuple().tm_yday:03d}')

# 8. Locale-Aware Formatting
def format_with_locale(dt: datetime, locale: str = 'en_US') -> str:
    """
    Format using locale settings

    Args:
        dt: Datetime object
        locale: Locale string

    Returns:
        Localized format
    """
    import locale
    try:
        locale.setlocale(locale.LC_TIME, locale)
        formatted = dt.strftime('%c')
        locale.setlocale(locale.LC_TIME, '')  # Reset
        return formatted
    except:
        return dt.strftime('%c')

# 9. Format Validation
def validate_format(format_string: str) -> bool:
    """
    Validate format string

    Args:
        format_string: Format string to validate

    Returns:
        True if valid
    """
    try:
        datetime.now().strftime(format_string)
        return True
    except:
        return False

def get_all_format_codes() -> dict:
    """
    Get all format codes with examples

    Returns:
        Dictionary of format codes
    """
    now = datetime(2025, 12, 31, 14, 30, 45)
    return {
        'Year': {
            '%Y': now.strftime('%Y'),  # 2025
            '%y': now.strftime('%y')   # 25
        },
        'Month': {
            '%m': now.strftime('%m'),  # 12
            '%B': now.strftime('%B'),  # December
            '%b': now.strftime('%b'),  # Dec
        },
        'Day': {
            '%d': now.strftime('%d'),  # 31
            '%A': now.strftime('%A'),  # Wednesday
            '%a': now.strftime('%a'),  # Wed
        },
        'Time': {
            '%H': now.strftime('%H'),  # 14
            '%I': now.strftime('%I'),  # 02
            '%M': now.strftime('%M'),  # 30
            '%S': now.strftime('%S'),  # 45
            '%p': now.strftime('%p'),  # PM
        }
    }

# Usage Examples
def demonstrate_time_formatting():
    print("=== Web Python Time Formatting Examples ===\n")

    now = datetime.now()

    # 1. Standard formats
    print("--- 1. Standard Format Codes ---")
    print(f"Month formats: {format_month(now)}")
    print(f"Day formats: {format_day(now)}")
    print(f"Time formats: {format_time(now)}")

    # 2. Common formats
    print("\n--- 2. Common Date Formats ---")
    print(f"ISO 8601: {format_iso8601(now)}")
    print(f"RFC 2822: {format_rfc2822(now)}")
    print(f"RFC 3339: {format_rfc3339(now)}")
    print(f"HTTP date: {format_http_date(now)}")

    # 3. Regional formats
    print("\n--- 3. Regional Formats ---")
    print(f"US: {format_us_date(now)}")
    print(f"EU: {format_eu_date(now)}")
    print(f"ISO: {format_iso_date(now)}")
    print(f"Chinese: {format_chinese_date(now)}")
    print(f"Japanese: {format_japanese_date(now)}")

    # 4. Custom formats
    print("\n--- 4. Custom Formats ---")
    print(f"Readable: {format_readable(now)}")
    print(f"Compact: {format_compact(now)}")
    print(f"With timezone: {format_with_timezone(now)}")
    print(f"Friendly: {format_friendly(now)}")

    # 5. Duration formatting
    print("\n--- 5. Duration Formatting ---")
    print(f"3661 seconds: {format_duration(3661)}")
    print(f"123.456 seconds: {format_duration_precise(123.456)}")

    # 6. Relative formatting
    print("\n--- 6. Relative Formatting ---")
    future = datetime(2025, 12, 31, 23, 59, 59)
    print(f"Relative to future: {format_relative_to_now(future)}")
    past = datetime(2025, 1, 1, 0, 0, 0)
    print(f"Relative to past: {format_relative_to_now(past)}")

    # 7. Business formats
    print("\n--- 7. Business Date Formats ---")
    print(f"Quarter: {format_quarter(now)}")
    print(f"Week number: {format_week_number(now)}")
    print(f"Day of year: {format_day_of_year(now)}")

    # 8. Format codes reference
    print("\n--- 8. Format Codes Reference ---")
    codes = get_all_format_codes()
    for category, items in codes.items():
        print(f"\n{category}:")
        for code, example in items.items():
            print(f"  {code}: {example}")

    print("\n=== All Time Formatting Examples Completed ===")

# Export functions
# export { format_year, format_month, format_day, format_time }
# export { format_iso8601, format_rfc2822, format_rfc3339, format_http_date }
# export { format_us_date, format_eu_date, format_iso_date, format_chinese_date, format_japanese_date }
# export { format_readable, format_compact, format_with_timezone, format_friendly }
# export { format_duration, format_duration_precise }
# export { format_relative_to_now }
# export { format_quarter, format_week_number, format_day_of_year }
# export { format_with_locale }
# export { validate_format, get_all_format_codes }
# export { demonstrate_time_formatting }

💻 Time Parsing python

🟡 intermediate ⭐⭐⭐

Parse strings into datetime objects using various formats and handle parsing errors

⏱️ 25 min 🏷️ python, web, datetime, parsing
Prerequisites: Intermediate Python, datetime module, strptime
# Web Python Time Parsing Examples
# Converting strings to datetime objects with various formats

# 1. Basic Parsing
from datetime import datetime
from typing import Optional, List
import re

def parse_iso8601(date_string: str) -> Optional[datetime]:
    """
    Parse ISO 8601 format

    Args:
        date_string: ISO format string

    Returns:
        Datetime object or None
    """
    try:
        return datetime.fromisoformat(date_string)
    except:
        return None

def parse_rfc2822(date_string: str) -> Optional[datetime]:
    """
    Parse RFC 2822 format

    Args:
        date_string: RFC 2822 format string

    Returns:
        Datetime object or None
    """
    try:
        from email.utils import parsedate_to_datetime
        return parsedate_to_datetime(date_string)
    except:
        return None

def parse_custom_format(date_string: str, format_string: str) -> Optional[datetime]:
    """
    Parse using custom format

    Args:
        date_string: Date string
        format_string: Format string

    Returns:
        Datetime object or None
    """
    try:
        return datetime.strptime(date_string, format_string)
    except:
        return None

# 2. Common Format Parsing
def parse_us_date(date_string: str) -> Optional[datetime]:
    """
    Parse US date (MM/DD/YYYY)

    Args:
        date_string: US format date

    Returns:
        Datetime object or None
    """
    formats = [
        '%m/%d/%Y',
        '%m/%d/%y',
        '%m-%d-%Y',
        '%m-%d-%y'
    ]
    for fmt in formats:
        result = parse_custom_format(date_string, fmt)
        if result:
            return result
    return None

def parse_eu_date(date_string: str) -> Optional[datetime]:
    """
    Parse European date (DD/MM/YYYY)

    Args:
        date_string: EU format date

    Returns:
        Datetime object or None
    """
    formats = [
        '%d/%m/%Y',
        '%d/%m/%y',
        '%d-%m-%Y',
        '%d-%m-%y'
    ]
    for fmt in formats:
        result = parse_custom_format(date_string, fmt)
        if result:
            return result
    return None

def parse_iso_date(date_string: str) -> Optional[datetime]:
    """
    Parse ISO date (YYYY-MM-DD)

    Args:
        date_string: ISO format date

    Returns:
        Datetime object or None
    """
    formats = [
        '%Y-%m-%d',
        '%Y%m%d',
        '%Y-%m-%d %H:%M:%S',
        '%Y-%m-%dT%H:%M:%S'
    ]
    for fmt in formats:
        result = parse_custom_format(date_string, fmt)
        if result:
            return result
    return None

# 3. Flexible Parsing
def parse_auto(date_string: str) -> Optional[datetime]:
    """
    Auto-detect and parse format

    Args:
        date_string: Date string

    Returns:
        Datetime object or None
    """
    # Try ISO 8601 first
    result = parse_iso8601(date_string)
    if result:
        return result

    # Try RFC 2822
    result = parse_rfc2822(date_string)
    if result:
        return result

    # Try common formats
    formats = [
        '%Y-%m-%d %H:%M:%S',
        '%Y-%m-%dT%H:%M:%S',
        '%Y-%m-%d',
        '%d/%m/%Y',
        '%m/%d/%Y',
        '%d.%m.%Y',
        '%m.%d.%Y',
        '%d %b %Y',
        '%d %B %Y',
        '%b %d, %Y',
        '%B %d, %Y',
        '%Y%m%d',
        '%d/%m/%y',
        '%m/%d/%y'
    ]

    for fmt in formats:
        try:
            return datetime.strptime(date_string, fmt)
        except:
            continue

    return None

def parse_auto_list(date_string: str) -> List[datetime]:
    """
    Parse and return all possible interpretations

    Args:
        date_string: Date string

    Returns:
        List of possible datetimes
    """
    results = []
    formats = [
        '%Y-%m-%d %H:%M:%S',
        '%Y-%m-%d',
        '%d/%m/%Y',
        '%m/%d/%Y',
        '%d.%m.%Y',
        '%m.%d.%Y'
    ]

    for fmt in formats:
        try:
            results.append(datetime.strptime(date_string, fmt))
        except:
            continue

    return results

# 4. Time Parsing
def parse_time(time_string: str) -> Optional[datetime]:
    """
    Parse time string

    Args:
        time_string: Time string

    Returns:
        Datetime object or None
    """
    formats = [
        '%H:%M:%S',
        '%H:%M',
        '%I:%M:%S %p',
        '%I:%M %p',
        '%H:%M:%S.%f',
        '%I:%M:%S.%f %p'
    ]

    for fmt in formats:
        try:
            parsed = datetime.strptime(time_string, fmt)
            return parsed
        except:
            continue

    return None

def parse_timestamp(timestamp: float) -> datetime:
    """
    Parse Unix timestamp

    Args:
        timestamp: Unix timestamp

    Returns:
        Datetime object
    """
    return datetime.fromtimestamp(timestamp)

def parse_timestamp_ms(timestamp: int) -> datetime:
    """
    Parse millisecond timestamp

    Args:
        timestamp: Millisecond timestamp

    Returns:
        Datetime object
    """
    return datetime.fromtimestamp(timestamp / 1000)

# 5. Relative Time Parsing
def parse_relative(relative_string: str) -> Optional[datetime]:
    """
    Parse relative time strings

    Args:
        relative_string: Relative time (e.g., "in 5 minutes", "2 hours ago")

    Returns:
        Datetime object or None
    """
    from datetime import timedelta
    import re

    now = datetime.now()

    # Match patterns like "5 minutes ago", "in 2 hours", etc.
    patterns = [
        (r'(\d+)\s+second[s]?\s+ago', lambda m: now - timedelta(seconds=int(m.group(1)))),
        (r'(\d+)\s+minute[s]?\s+ago', lambda m: now - timedelta(minutes=int(m.group(1)))),
        (r'(\d+)\s+hour[s]?\s+ago', lambda m: now - timedelta(hours=int(m.group(1)))),
        (r'(\d+)\s+day[s]?\s+ago', lambda m: now - timedelta(days=int(m.group(1)))),
        (r'\s+in\s+(\d+)\s+second[s]?', lambda m: now + timedelta(seconds=int(m.group(1)))),
        (r'\s+in\s+(\d+)\s+minute[s]?', lambda m: now + timedelta(minutes=int(m.group(1)))),
        (r'\s+in\s+(\d+)\s+hour[s]?', lambda m: now + timedelta(hours=int(m.group(1)))),
        (r'\s+in\s+(\d+)\s+day[s]?', lambda m: now + timedelta(days=int(m.group(1)))),
    ]

    for pattern, calculator in patterns:
        match = re.search(pattern, relative_string, re.IGNORECASE)
        if match:
            return calculator(match)

    return None

# 6. Multi-Format Parsing
def try_multiple_formats(date_string: str, formats: List[str]) -> Optional[datetime]:
    """
    Try multiple formats

    Args:
        date_string: Date string
        formats: List of format strings

    Returns:
        First successful parse or None
    """
    for fmt in formats:
        try:
            return datetime.strptime(date_string, fmt)
        except:
            continue
    return None

# 7. Parser with Fallback
def parse_with_fallback(date_string: str, fallback: Optional[datetime] = None) -> Optional[datetime]:
    """
    Parse with fallback on failure

    Args:
        date_string: Date string
        fallback: Fallback datetime

    Returns:
        Parsed datetime or fallback
    """
    result = parse_auto(date_string)
    return result if result else fallback

# 8. Validation
def is_valid_date(date_string: str, format_string: str) -> bool:
    """
    Validate date string against format

    Args:
        date_string: Date string
        format_string: Format string

    Returns:
        True if valid
    """
    try:
        datetime.strptime(date_string, format_string)
        return True
    except:
        return False

def get_detected_format(date_string: str) -> Optional[str]:
    """
    Detect which format matches

    Args:
        date_string: Date string

    Returns:
        Format string or None
    """
    formats = [
        '%Y-%m-%d',
        '%d/%m/%Y',
        '%m/%d/%Y',
        '%Y-%m-%d %H:%M:%S',
        '%Y-%m-%dT%H:%M:%S',
        '%d %b %Y',
        '%b %d, %Y'
    ]

    for fmt in formats:
        if is_valid_date(date_string, fmt):
            return fmt

    return None

# 9. Extract Date Parts
def extract_date_parts(date_string: str) -> Optional[dict]:
    """
    Extract date parts using regex

    Args:
        date_string: Date string

    Returns:
        Dictionary with parts or None
    """
    # Try ISO format
    match = re.match(r'(\d{4})-(\d{2})-(\d{2})', date_string)
    if match:
        return {
            'year': int(match.group(1)),
            'month': int(match.group(2)),
            'day': int(match.group(3))
        }

    # Try US format
    match = re.match(r'(\d{2})/(\d{2})/(\d{4})', date_string)
    if match:
        return {
            'month': int(match.group(1)),
            'day': int(match.group(2)),
            'year': int(match.group(3))
        }

    # Try EU format
    match = re.match(r'(\d{2})/(\d{2})/(\d{4})', date_string)
    if match:
        return {
            'day': int(match.group(1)),
            'month': int(match.group(2)),
            'year': int(match.group(3))
        }

    return None

# Usage Examples
def demonstrate_time_parsing():
    print("=== Web Python Time Parsing Examples ===\n")

    # 1. Basic parsing
    print("--- 1. Basic Parsing ---")
    iso = "2025-12-31T14:30:45"
    print(f"ISO string: {iso}")
    print(f"Parsed: {parse_iso8601(iso)}")

    custom = "31/12/2025"
    format = "%d/%m/%Y"
    print(f"\nCustom: {custom} with format {format}")
    print(f"Parsed: {parse_custom_format(custom, format)}")

    # 2. Common formats
    print("\n--- 2. Common Format Parsing ---")
    us = "12/31/2025"
    print(f"US date '{us}': {parse_us_date(us)}")

    eu = "31/12/2025"
    print(f"EU date '{eu}': {parse_eu_date(eu)}")

    iso = "2025-12-31"
    print(f"ISO date '{iso}': {parse_iso_date(iso)}")

    # 3. Auto-detect
    print("\n--- 3. Auto-Detection ---")
    test_dates = ["2025-12-31", "31/12/2025", "12/31/2025", "Dec 31, 2025"]
    for date in test_dates:
        parsed = parse_auto(date)
        print(f"'{date}' -> {parsed}")

    # 4. Time parsing
    print("\n--- 4. Time Parsing ---")
    times = ["14:30:45", "2:30 PM", "14:30"]
    for t in times:
        parsed = parse_time(t)
        print(f"'{t}' -> {parsed}")

    # 5. Timestamp parsing
    print("\n--- 5. Timestamp Parsing ---")
    ts = 1735667445
    print(f"Timestamp {ts}: {parse_timestamp(ts)}")

    # 6. Relative time
    print("\n--- 6. Relative Time Parsing ---")
    relative = ["in 5 minutes", "2 hours ago", "3 days ago"]
    for rel in relative:
        parsed = parse_relative(rel)
        print(f"'{rel}' -> {parsed}")

    # 7. Multi-format
    print("\n--- 7. Try Multiple Formats ---")
    formats = ['%Y-%m-%d', '%d/%m/%Y', '%m/%d/%Y']
    result = try_multiple_formats("2025-12-31", formats)
    print(f"Result: {result}")

    # 8. Validation
    print("\n--- 8. Validation ---")
    valid = is_valid_date("2025-12-31", "%Y-%m-%d")
    print(f"Is '2025-12-31' valid for '%Y-%m-%d': {valid}")

    invalid = is_valid_date("31-12-2025", "%Y-%m-%d")
    print(f"Is '31-12-2025' valid for '%Y-%m-%d': {invalid}")

    # 9. Format detection
    print("\n--- 9. Format Detection ---")
    test = "31/12/2025"
    detected = get_detected_format(test)
    print(f"Detected format for '{test}': {detected}")

    # 10. Extract parts
    print("\n--- 10. Extract Date Parts ---")
    parts = extract_date_parts("2025-12-31")
    print(f"Parts: {parts}")

    print("\n=== All Time Parsing Examples Completed ===")

# Export functions
# export { parse_iso8601, parse_rfc2822, parse_custom_format }
# export { parse_us_date, parse_eu_date, parse_iso_date }
# export { parse_auto, parse_auto_list }
# export { parse_time, parse_timestamp, parse_timestamp_ms }
# export { parse_relative }
# export { try_multiple_formats }
# export { parse_with_fallback }
# export { is_valid_date, get_detected_format }
# export { extract_date_parts }
# export { demonstrate_time_parsing }