๐ 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}")