Paramclasses Academy - Blog

Tutorials Details

←
Post 18 of 20
→

Python Date and Time, Regular Expressions (Regex) & Pattern Matching

Python Date and Time, Regular Expressions (Regex) & Pattern Matching

October 17, 2026

Python Date and Time, Regular Expressions (Regex) & Pattern Matching

Introduction

Python provides powerful tools for working with dates, times, and text patterns. The datetime module helps manage dates and time values, while the re module supports regular expressions for searching, validating, and replacing text.

Python also supports structural pattern matching through the match and case statements, introduced in Python 3.10.

In this tutorial, you will learn:

  • Working with dates and times

  • Formatting and parsing dates

  • Date calculations using timedelta

  • Introduction to regular expressions

  • Common regex patterns

  • Searching, matching, and replacing text

  • Validating email and phone number formats

  • Structural pattern matching with match and case

  • Practical examples and interview questions

1. Working with Dates in Python

Python provides the datetime module to work with dates and times.

Example

from datetime import date

today = date.today()

print("Today's Date:", today)
print("Year:", today.year)
print("Month:", today.month)
print("Day:", today.day)

Example Output

Today's Date: 2026-10-17
Year: 2026
Month: 10
Day: 17

The output depends on the date when the program runs.

The date.today() method returns the current local date.

2. Working with Time in Python

The time class represents a time of day independently of a date.

Example

from datetime import time

current_time = time(14, 30, 45)

print("Time:", current_time)
print("Hour:", current_time.hour)
print("Minute:", current_time.minute)
print("Second:", current_time.second)

Output

Time: 14:30:45
Hour: 14
Minute: 30
Second: 45

This example creates a time value. It does not retrieve the current system time.

3. Getting the Current Date and Time

Use datetime.now() to retrieve the current local date and time.

Example

from datetime import datetime

now = datetime.now()

print("Current Date and Time:", now)
print("Current Year:", now.year)
print("Current Month:", now.month)
print("Current Day:", now.day)

The exact output depends on the computer's local clock and time zone.

For applications that require a specific time zone, use Python's zoneinfo module or another appropriate time-zone-aware approach.

4. Formatting Dates with strftime()

The strftime() method converts a date or time value into a formatted string.

Example

from datetime import datetime

now = datetime.now()

formatted_date = now.strftime("%d-%m-%Y")
formatted_time = now.strftime("%I:%M %p")

print("Date:", formatted_date)
print("Time:", formatted_time)

Common formatting codes:

Code Meaning Example
%d Day of the month 17
%m Month number 10
%Y Four-digit year 2026
%y Two-digit year 26
%H Hour in 24-hour format 14
%I Hour in 12-hour format 02
%M Minutes 30
%S Seconds 45
%p AM or PM PM
%A Full weekday name Saturday
%B Full month name October

The actual values depend on the date and time used.

5. Converting Strings into Dates with strptime()

The strptime() method parses a string into a datetime object using a specified format.

Example

from datetime import datetime

date_string = "17-10-2026"

parsed_date = datetime.strptime(date_string, "%d-%m-%Y")

print(parsed_date)
print(parsed_date.year)

Output

2026-10-17 00:00:00
2026

The format provided to strptime() must match the input string. Invalid date values or mismatched formats raise ValueError.

6. Date Calculations with timedelta

The timedelta class represents a duration. It can be used to add or subtract days, seconds, and other supported time units from dates and datetimes.

Example

from datetime import date, timedelta

today = date.today()

tomorrow = today + timedelta(days=1)
yesterday = today - timedelta(days=1)

print("Today:", today)
print("Tomorrow:", tomorrow)
print("Yesterday:", yesterday)

This example calculates dates relative to the current date.

Calculating the Difference Between Dates

from datetime import date

start_date = date(2026, 10, 1)
end_date = date(2026, 10, 17)

difference = end_date - start_date

print("Days Between:", difference.days)

Output:

Days Between: 16

Date differences are useful for calculating deadlines, booking periods, and the number of days between events.

7. What Is a Regular Expression (Regex)?

A regular expression is a sequence of characters that defines a text-search pattern.

Python provides the built-in re module for working with regular expressions.

Regex can be used for:

  • Searching for specific text

  • Validating input formats

  • Extracting numbers or words

  • Replacing text

  • Splitting strings using patterns

Example

import re

text = "Python is easy to learn."

result = re.search("Python", text)

if result:
    print("Pattern found!")
else:
    print("Pattern not found.")

Output

Pattern found!

The re.search() function looks for the pattern anywhere in the string.

8. Common Regular Expression Symbols

Symbol Meaning
. Matches any character except a newline by default
^ Matches the beginning of a string
$ Matches the end of a string
* Matches zero or more repetitions
+ Matches one or more repetitions
? Matches zero or one repetition
\d Matches a digit
\D Matches a non-digit
\w Matches a word character
\s Matches whitespace
[abc] Matches one of the specified characters
[0-9] Matches a digit from 0 to 9
{n} Matches exactly n repetitions
{n,m} Matches between n and m repetitions

Use raw strings such as r"\d+" for most regex patterns in Python. This makes backslashes easier to manage.

9. Using re.findall()

The re.findall() function returns all non-overlapping matches as a list.

Example

import re

text = "I have 10 apples and 20 oranges."

numbers = re.findall(r"\d+", text)

print(numbers)

Output

['10', '20']

The pattern \d+ matches one or more consecutive digits.

10. Using re.match() and re.search()

Both functions search for a regex pattern, but they differ in where matching begins.

  • re.match() checks for a match at the beginning of the string.

  • re.search() scans the string for the first match.

Example

import re

text = "Python programming"

print(bool(re.match(r"Python", text)))
print(bool(re.search(r"programming", text)))

Output

True
True

A pattern can be found by search() even when it does not occur at the beginning of the string.

11. Validating a Phone Number Format

Regex can check whether input follows a specified format. The following example checks for exactly ten digits.

Example

import re

phone = "9876543210"

if re.fullmatch(r"\d{10}", phone):
    print("Valid format")
else:
    print("Invalid format")

Output

Valid format

This validates the format only. It does not prove that the phone number is assigned, active, or reachable.

12. Checking an Email Address Format

Regular expressions can perform basic email-format checks, although complete email validation is more complicated.

Example

import re

email = "student@example.com"

pattern = r"^[\w.+-]+@[\w-]+(?:\.[\w-]+)+$"

if re.fullmatch(pattern, email):
    print("Email format looks valid")
else:
    print("Invalid email format")

Output

Email format looks valid

This pattern performs a simplified format check. For production applications, use appropriate email validation libraries and verification processes where necessary.

13. Replacing Text with re.sub()

The re.sub() function replaces occurrences of a regex pattern with another string.

Example

import re

text = "My phone number is 9876543210"

result = re.sub(r"\d", "*", text)

print(result)

Output

My phone number is **********

The function replaces each digit with an asterisk while keeping the remaining text unchanged.

## 14. Splitting Text with `re.split()`

The `re.split()` function splits a string wherever the specified pattern matches.

### Example

```python
import re

text = "apple,banana;orange mango"

result = re.split(r"[,;\s]+", text)

print(result)

Output

['apple', 'banana', 'orange', 'mango']

The pattern splits the string on commas, semicolons, or whitespace.

15. What Is Pattern Matching in Python?

Structural pattern matching uses the match and case statements to compare a value against different patterns. It was introduced in Python 3.10.

It can make complex branching logic easier to organize.

Example

def check_day(day):
    match day:
        case 1:
            return "Monday"
        case 2:
            return "Tuesday"
        case 3:
            return "Wednesday"
        case _:
            return "Other day"

print(check_day(1))
print(check_day(3))
print(check_day(7))

Output

Monday
Wednesday
Other day

The underscore pattern _ acts as a catch-all case when placed last.

16. Pattern Matching with Multiple Values

You can match multiple literal values in one case using the | pattern.

Example

def get_day_type(day):
    match day:
        case "Saturday" | "Sunday":
            return "Weekend"
        case "Monday" | "Tuesday" | "Wednesday" | "Thursday" | "Friday":
            return "Weekday"
        case _:
            return "Invalid day"

print(get_day_type("Sunday"))
print(get_day_type("Wednesday"))

Output

Weekend
Weekday

This is useful when several values should produce the same result.

17. Pattern Matching with Dictionaries

Structural pattern matching can also check dictionary structures.

Example

def describe_user(user):
    match user:
        case {"name": name, "role": "admin"}:
            return f"{name} is an administrator."
        case {"name": name, "role": "student"}:
            return f"{name} is a student."
        case _:
            return "Unknown user"

print(describe_user({"name": "Amit", "role": "admin"}))
print(describe_user({"name": "Neha", "role": "student"}))

Output

Amit is an administrator.
Neha is a student.

The dictionary patterns match the required keys and values. Additional keys are allowed in these patterns.

18. Practical Example: Event Deadline Calculator

This example combines date parsing and date arithmetic to calculate a deadline.

from datetime import datetime, timedelta

start_date = input("Enter start date (DD-MM-YYYY): ")

try:
    parsed_date = datetime.strptime(start_date, "%d-%m-%Y")
    deadline = parsed_date + timedelta(days=7)

    print("Start Date:", parsed_date.strftime("%d-%m-%Y"))
    print("Deadline:", deadline.strftime("%d-%m-%Y"))

except ValueError:
    print("Please enter a valid date in DD-MM-YYYY format.")

Example Input

17-10-2026

Example Output

Start Date: 17-10-2026
Deadline: 24-10-2026

This program validates the date format, calculates a deadline seven days later, and handles invalid input.

19. Common Mistakes to Avoid

  1. Using the wrong format string with strptime().

  2. Confusing re.match() with re.search().

  3. Forgetting that re.findall() returns a list.

  4. Assuming a regex format check proves that an email address or phone number is real.

  5. Using overly complicated regular expressions when simpler string methods would work.

  6. Using match and case in a Python version earlier than 3.10.

  7. Forgetting to include a catch-all case _: when a fallback is required.

  8. Ignoring time zones when handling timestamps across different regions.

20. Python Date, Time, and Regex Practice Questions

  1. Display the current date using Python.

  2. Display the current date and time.

  3. Format a date as DD-MM-YYYY.

  4. Convert a date string into a datetime object.

  5. Calculate the date seven days from today.

  6. Extract all numbers from a sentence using regex.

  7. Check whether a string contains exactly ten digits.

  8. Replace every digit in a string with *.

  9. Split a string using commas and spaces.

  10. Use match and case to categorize a day as a weekday or weekend.

21. Python Interview Questions and Answers

Q1. Which module is used for date and time operations in Python?

The datetime module provides classes for working with dates, times, and durations.

Q2. What is the difference between strftime() and strptime()?

strftime() formats a date or time as a string. strptime() parses a string into a date/time object using a specified format.

Q3. What is timedelta?

timedelta represents a duration and supports date and time arithmetic.

Q4. What is a regular expression?

A regular expression is a pattern used to search, validate, extract, or replace text.

Q5. What is the purpose of the re module?

The re module provides Python's regular-expression operations.

Q6. What is the difference between re.match() and re.search()?

re.match() checks at the beginning of the string, while re.search() scans for the first match anywhere in the string.

Q7. What does re.findall() return?

It returns a list of all non-overlapping matches.

Q8. What does re.sub() do?

It replaces occurrences of a pattern with a replacement string.

Q9. What is structural pattern matching?

It is a Python feature using match and case to compare values or structures against patterns.

Q10. Which Python version introduced match and case?

Python 3.10.

Conclusion

Python's date and time tools help manage dates, deadlines, and durations. Regular expressions make text searching and format checking more flexible, while structural pattern matching provides a clear way to handle multiple data patterns.

Practice these concepts with small programs to strengthen your Python skills and prepare for interviews and real-world development.

←
Post 18 of 20
→