Home Tutorials Python Tutorial Dates and Math
Dates and Math

Dates and Math


Definition: Python includes built-in libraries to handle specialized data calculations. The datetime module provides classes for manipulating dates and times, while the math module provides access to mathematical functions defined by the C standard.

Why: Handling dates, tracking time, and performing complex mathematical formulas are universal requirements in programming. Python packages these tools into standard modules so you don't have to build complex calculations from scratch.

1. Working with Dates and Time (The datetime Module)

The datetime module allows you to capture the current time, format calendar dates, calculate time deltas (differences), and log timestamps.

Example

import datetime

# Capturing the exact current date and time
now = datetime.datetime.now()
print(now)

# Creating a specific date
specific_date = datetime.date(2026, 5, 5)
print(specific_date)

2. Working with Advanced Mathematics (The math Module)

While basic math operators like +, -, *, and / are built directly into Python, the math module expands your toolkit with advanced operations like trigonometry, logarithms, power functions, and rounding rules.

Example

import math

# Rounding numbers up and down
print(math.ceil(4.2))   # Output: 5 (Rounds UP to nearest integer)
print(math.floor(4.8))  # Output: 4 (Rounds DOWN to nearest integer)

# Common mathematical constants and powers
print(math.pi)          # Output: 3.141592653589793
print(math.pow(2, 3))   # Output: 8.0 (2 raised to the power of 3)

Key Notes

  • Data Type Output: The datetime.datetime.now() function returns a specialized object, not a simple string. If you want to display it neatly to a user, you use the .strftime() method to format it.
  • Floats vs. Integers: Many functions in the math module (like math.pow() or math.sqrt()) return a float value (e.g., 8.0 instead of 8), even if the answer is a whole number.
  • Both modules are part of Python's Standard Library, meaning they are included out-of-the-box when you install Python and do not require external installation via pip.
Example

🏋️ Test Yourself With Exercises

Take our quiz on Dates and Math to test your knowledge.

Exercise »