Regular Expressions & Date/Time Management
An authoritative reference manual on NFA regular expression engine matching (re module), sequence/special characters, HTML web scraping, datetime, strftime/strptime, POSIX Epoch timestamps, and calendar operations.
Text pattern matching and temporal data handling are indispensable programming skills. This chapter explores regular expression pattern matching with the `re` module, NFA state machine execution, HTML information extraction, and date/time operations using `datetime`, `time`, and `calendar`.
8.1. 1. Regular Expressions (`re` Module) & Pattern Matching
Definition: Regular Expressions provide a powerful Domain Specific Language (DSL) backed by an NFA (Nondeterministic Finite Automata) engine for pattern matching, searching, and replacing text.
Core Working Principles:
- Sequence Characters: `\d` (digit 0-9), `\w` (word character a-z, A-Z, 0-9, _), `\s` (whitespace space/tab/newline), `\D`, `\W`, `\S` (negations).
- Special Metacharacters: `^` (start of string), `$` (end of string), `.` (any char except newline), `*` (0+ repetitions), `+` (1+ repetitions), `?` (0 or 1 repetition), `[a-z]` (character class), `(group)` (capturing group).
- `re` Functions: `re.search()` (finds first match), `re.match()` (matches at start), `re.findall()` (returns all matches as a list), `re.sub()` (replaces matches). Use raw string literals `r'pattern'` to avoid backslash escaping conflicts.
Standard Search (find): Searches for an exact literal word like "cat".
Regular Expression (re): Like a smart metal detector configured to find any valid credit card number, email address, or phone number regardless of what numbers it contains!
import re
html_content = """
<div class="contact">
<p>Email: support@shafi-institute.edu</p>
<p>Phone: +91-98765-43210</p>
<a href="https://shafi-institute.edu/courses">Courses</a>
</div>
"""
# Extract Emails using Regex
email_pattern = r'[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}'
emails = re.findall(email_pattern, html_content)
# Extract Hyperlinks using Regex
url_pattern = r'href="(https?://[^"]+)"'
urls = re.findall(url_pattern, html_content)
print("Extracted Emails:", emails)
print("Extracted URLs:", urls)
5-Marks Exam Scoring Points
- re.findall() returns all non-overlapping pattern matches in a string as a list.
- Use raw string syntax r'pattern' for regex patterns to avoid backslash escaping issues.
- Regex metacharacters allow pattern extraction from HTML/text files.
8.2. 2. Date & Time Management (`datetime`, `time`, `calendar`)
Definition: Python manages dates, times, durations, and calendar calculations through the `datetime`, `time`, and `calendar` standard modules.
Core Working Principles:
- Core `datetime` Classes: `date`, `time`, `datetime`, `timedelta` (representing time differences).
- Formatting & Parsing:
- • `strftime(format)`: String Format Time (Converts datetime object $\rightarrow$ Formatted String).
- • `strptime(string, format)`: String Parse Time (Parses String $\rightarrow$ datetime object).
- Date Arithmetic & POSIX Epochs: Adding/subtracting `timedelta` objects; sorting lists of dates; inspecting Unix Epoch timestamps.
- Execution Timing & Calendar: Timing code execution with `time.perf_counter()`; generating calendar months with `calendar.month(year, month)`.
| Format Code | Description | Example Output |
|---|---|---|
%Y / %y |
Year (4-digit / 2-digit) | 2026 / 26 |
%m / %B |
Month (2-digit zero-padded / Full name) | 08 / August |
%d / %A |
Day of month / Full weekday name | 19 / Wednesday |
%H : %M : %S |
24-hour Hour : Minute : Second | 17 : 45 : 30 |
from datetime import datetime, timedelta
import time
import calendar
# Timing Code Execution
start_time = time.perf_counter()
now = datetime.now()
formatted_now = now.strftime("%Y-%m-%d %H:%M:%S (%A)")
# Date Arithmetic
future_date = now + timedelta(days=30)
# Parsing String to Datetime
date_str = "2026-12-31 23:59:59"
parsed_dt = datetime.strptime(date_str, "%Y-%m-%d %H:%M:%S")
end_time = time.perf_counter()
execution_duration = end_time - start_time
print(f"Current Time: {formatted_now}")
print(f"30 Days Later: {future_date.strftime('%Y-%m-%d')}")
print(f"Execution Elapsed Time: {execution_duration:.6f} seconds")
5-Marks Exam Scoring Points
- strftime converts datetime objects to strings; strptime parses strings into datetime objects.
- timedelta handles date addition, subtraction, and interval duration math.
- time.perf_counter() provides high-precision timing for measuring code execution performance.
✍️ Chapter 8 Reference Exercises & Review Problems
import re
sample_text = "Contact us at info@example.com or support@shafi.org. Call 9876543210 or 1234567890."
# Regex patterns
email_pattern = r'[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}'
phone_pattern = r'\b\d{10}\b'
found_emails = re.findall(email_pattern, sample_text)
found_phones = re.findall(phone_pattern, sample_text)
print("Emails:", found_emails) # ['info@example.com', 'support@shafi.org']
print("Phones:", found_phones) # ['9876543210', '1234567890']
- **`strftime()` (String Format Time):** Converts an in-memory `datetime` object into a human-readable formatted **String** representation based on format codes (e.g. `now.strftime('%Y-%m-%d')` $\rightarrow$ `'2026-08-19'`).
- **`strptime()` (String Parse Time):** Parses an input text **String** into a structured in-memory **`datetime` object** by supplying the matching format string (e.g. `datetime.strptime('2026-08-19', '%Y-%m-%d')` $\rightarrow$ `datetime(2026, 8, 19, 0, 0)`).