Python Datetime


In Python, datetime is a built-in module used to handle dates and times in a simple and effective way. Working with dates and times is common in almost every real-world application, including logging events, scheduling tasks, and calculating durations. Python’s datetime module provides classes to handle date, time, datetime, timedelta, and timezone operations efficiently.

This tutorial will guide you through creating, formatting, manipulating, and performing operations with dates and times in Python.

The datetime Module Overview

Python’s datetime module includes several important classes:

  • date – Represents a calendar date (year, month, day)

  • time – Represents time (hour, minute, second, microsecond)

  • datetime – Combines date and time

  • timedelta – Represents a duration or difference between two dates/times

  • timezone – Represents time zone information

Each class provides methods and attributes to access, manipulate, and format dates and times.

Importing the datetime Module

You can import the entire module or specific classes:

import datetime

# or import specific classes
from datetime import date, time, datetime, timedelta

Working with Dates

The date class represents a calendar date with year, month, and day.

Creating a Date

from datetime import date

d = date(2025, 11, 20)
print(d)             # Output: 2025-11-20
print(d.year)        # Output: 2025
print(d.month)       # Output: 11
print(d.day)         # Output: 20

Getting Today’s Date

today = date.today()
print(today)         # Output: current date

Formatting Dates

You can convert a date to a string in different formats using strftime:

today = date.today()
formatted_date = today.strftime("%d-%m-%Y")
print(formatted_date)  # Output: 20-11-2025

Common format codes:

Code Description
%d Day of the month
%m Month (01–12)
%Y Year (4 digits)
%A Full weekday name
%B Full month name

Working with Time

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

from datetime import time

t = time(14, 30, 15)  # 14:30:15
print(t.hour)         # Output: 14
print(t.minute)       # Output: 30
print(t.second)       # Output: 15

You can also include microseconds and timezone info:

t = time(14, 30, 15, 500000)
print(t.microsecond)  # Output: 500000

Working with Datetime

The datetime class combines date and time into a single object.

Creating a Datetime Object

from datetime import datetime

dt = datetime(2025, 11, 20, 14, 30, 15)
print(dt)          # Output: 2025-11-20 14:30:15

Getting Current Date and Time

now = datetime.now()
print(now)         # Output: current date and time

Accessing Attributes

print(now.year)
print(now.month)
print(now.day)
print(now.hour)
print(now.minute)
print(now.second)

Formatting Datetime

formatted_dt = now.strftime("%d-%m-%Y %H:%M:%S")
print(formatted_dt)  # Output: 20-11-2025 14:30:15

Parsing Strings to Datetime

You can convert strings into datetime objects using strptime:

dt_str = "20-11-2025 14:30:15"
dt_obj = datetime.strptime(dt_str, "%d-%m-%Y %H:%M:%S")
print(dt_obj)       # Output: 2025-11-20 14:30:15

This is useful when reading dates from files or user input.

Working with Timedelta

timedelta represents a duration or difference between two dates or times.

from datetime import timedelta, date

today = date.today()
delta = timedelta(days=10)

future_date = today + delta
past_date = today - delta

print(future_date)  # Date 10 days from today
print(past_date)    # Date 10 days before today

timedelta can also include hours, minutes, seconds, weeks:

delta = timedelta(weeks=2, hours=5, minutes=30)

Date Arithmetic

You can perform arithmetic with dates and times:

from datetime import datetime, timedelta

dt1 = datetime(2025, 11, 20, 14, 0, 0)
dt2 = datetime(2025, 11, 25, 16, 30, 0)

difference = dt2 - dt1
print(difference)          # Output: 5 days, 2:30:00
print(difference.days)     # Output: 5
print(difference.seconds)  # Output: 9000 (2 hours 30 minutes)

Timezone Handling

Python 3.2+ supports timezones using the timezone class:

from datetime import datetime, timezone, timedelta

utc_time = datetime.now(timezone.utc)
print(utc_time)

# Creating a custom timezone (UTC+5:30)
ist = timezone(timedelta(hours=5, minutes=30))
ist_time = datetime.now(ist)
print(ist_time)

Timezones are important when working with international applications or APIs.

Practical Examples

  1. Logging the current date and time:

now = datetime.now()
print(f"Log entry created at: {now.strftime('%d-%m-%Y %H:%M:%S')}")
  1. Calculating age from birthdate:

birthdate = date(1995, 6, 15)
today = date.today()
age = today.year - birthdate.year
if (today.month, today.day) < (birthdate.month, birthdate.day):
    age -= 1
print(age)
  1. Scheduling an event 7 days from now:

event_date = datetime.now() + timedelta(days=7)
print(event_date.strftime("%d-%m-%Y %H:%M:%S"))
  1. Calculating difference between two dates:

d1 = date(2025, 11, 20)
d2 = date(2025, 12, 25)
print(d2 - d1)  # Output: 35 days, 0:00:00
  1. Converting user input into datetime:

user_input = "25-12-2025 18:00:00"
dt_obj = datetime.strptime(user_input, "%d-%m-%Y %H:%M:%S")
print(dt_obj)

Summary of the Tutorial

The datetime module is a powerful tool in Python for working with dates and times. It provides classes to handle date, time, datetime, timedelta, and timezone, allowing you to create, format, manipulate, and perform arithmetic operations on date and time objects. By mastering the datetime module, you can efficiently manage real-world tasks like logging, scheduling, calculating durations, and handling international timezones.

Understanding datetime is essential for any Python programmer, as almost every application interacts with dates or times in some way. With practice, you will be able to perform complex date calculations and formatting with ease.


Practice Questions

  1. Print today’s date using the date class.

  2. Print the current time using the datetime module.

  3. Create a datetime object for 25th December 2025, 18:30:00 and print it.

  4. Format the current datetime as "DD-MM-YYYY HH:MM:SS".

  5. Convert the string "20-11-2025 14:30:00" into a datetime object using strptime().

  6. Calculate the number of days between 1st January 2025 and 20th November 2025.

  7. Add 10 days to today’s date and print the result.

  8. Subtract 3 hours and 45 minutes from the current datetime.

  9. Create a timezone-aware datetime for UTC+5:30 and print it.

  10. Calculate the age of a person born on 15th June 1995 using today’s date.


Try a Short Quiz.

coding learning websites codepractice

No quizzes available.

Go Back Top