๐Ÿ“† Mastering Python Date and Time Functions: Real-World Examples

PYTHON

5/5/20253 min read

Dates and times are essential in almost every real-world application โ€” from logging, reporting, and automation to data analysis and scheduling. Python provides powerful tools through its built-in datetime module to handle all of these tasks efficiently.

In this blog, weโ€™ll walk through the most commonly used date/time functions, with practical examples youโ€™ll actually use.

๐Ÿงฐ 1. Getting Started with datetime

from datetime import datetime, date, time, timedelta

The core classes:

  • datetime โ€” full date and time

  • date โ€” only the date

  • time โ€” only the time

  • timedelta โ€” differences between two dates or times

๐Ÿ“ 2. Get Current Date and Time

from datetime import datetime, date, time, timedelta

now = datetime.now()

print(now) # 2025-05-03 14:23:51.289393

โœ… Use case: Timestamping logs, file names, or records.

๐Ÿ“… 3. Create Specific Dates

birthday = date(1995, 10, 12)

print(birthday) # 1995-10-12

โœ… Use case: Storing fixed dates for birthdays, due dates, etc.

๐Ÿ• 4. Extract Parts of a Date or Time

now = datetime.now()

print(now.year) # 2025

print(now.month) # 5

print(now.day) # 3

print(now.hour) # 14

โœ… Use case: Filter data by month/year or group sales by day of the week.

๐Ÿ” 5. Date Arithmetic with timedelta

today = date.today()

yesterday = today - timedelta(days=1)

next_week = today + timedelta(weeks=1)

print(yesterday, next_week)

โœ… Use case: Calculate deadlines, reminders, or subscriptions.

๐Ÿ“† 6. Formatting Dates with strftime()

strftime() is a method in Python used to format date and time objects into readable strings.

now = datetime.now()

formatted = now.strftime("%d-%m-%Y %H:%M")

print(formatted) # 03-05-2025 14:25

โœ… Use case: Creating readable timestamps for reports and logs.

๐Ÿงญ 7. Parsing Strings to Dates with strptime()

date_str = "03-05-2025"

parsed = datetime.strptime(date_str, "%d-%m-%Y")

print(parsed) # 2025-05-03 00:00:00

โœ… Use case: Convert date columns in CSV files into datetime objects.

๐Ÿ—ƒ๏ธ 8. Working with Dates in Pandas

import pandas as pd

df = pd.DataFrame({

'created_at': ['2025-01-01', '2025-03-15', '2025-04-25']

})

df['created_at'] = pd.to_datetime(df['created_at'])

df['month'] = df['created_at'].dt.month

df['day_name'] = df['created_at'].dt.day_name()

โœ… Use case: Analyze user sign-ups or orders by day of the week or month.

๐Ÿ” 9. Loop Through Dates in a Range

start = date(2025, 5, 1)

end = date(2025, 5, 5)

delta = timedelta(days=1)

while start <= end:

print(start)

start += delta

โœ… Use case: Automate daily reports or scrape pages by date.

๐Ÿ“Š 10. Calculate Age or Duration Between Two Dates

from datetime import datetime

dob = datetime(1990, 4, 5)

today = datetime.today()

age = (today - dob).days // 365

print(f"Age is: {age} years")

โœ… Use case: Age calculation, subscription length, or membership duration.

๐ŸŒŽ 11. Time Zones with pytz

from datetime import datetime

import pytz

utc = pytz.utc

local = pytz.timezone("Asia/Kolkata")

now_utc = datetime.now(utc)

now_local = now_utc.astimezone(local)

print(now_local.strftime("%Y-%m-%d %H:%M:%S %Z"))

โœ… Use case: Time zone aware scheduling for global apps.

โฑ๏ธ 12. Measure Execution Time

import time

start = time.time()

# Simulated task

time.sleep(2)

end = time.time()

print(f"Took {end - start:.2f} seconds")

โœ… Use case: Benchmarking code or optimizing slow tasks.

๐Ÿ“ฆ 13. Auto-Generate File Names with Timestamps

timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")

filename = f"backup_{timestamp}.csv"

print(filename)

โœ… Use case: Versioning backups, reports, or logs.

๐Ÿš€ Summary

Pythonโ€™s datetime module, when combined with pandas and pytz, is a must-have toolkit for time-sensitive applications like analytics, reporting, automation, and data cleaning.

Kishore Babu Valluri

Senior Data Scientist | Freelance Consultant | AI/ML & GenAI Expert

With deep expertise in machine learning, artificial intelligence, and Generative AI, I work as a Senior Data Scientist, freelance consultant, and AI agent developer. I help businesses unlock value through intelligent automation, predictive modeling, and cutting-edge AI solutions.

โœ… 14. Accurate Way to Calculate Month Difference

from datetime import date

from dateutil.relativedelta import relativedelta

dob = date(1990, 4, 15)

today = date.today()

diff = relativedelta(today, dob)

total_months = diff.years * 12 + diff.months

print(f"Age in months: {total_months}")