Skip to main content

what is Python Date and Time ? Complete Guide with Examples:

 

✍️Introduction

Python provides powerful tools to work with dates and times.
The most commonly used module is datetime.

The datetime module allows Python programs to create, manipulate, format, and perform calculations with dates and times easily.

Date and time handling is used in:

  • Logging systems

  • Attendance & billing systems

  • Data analysis

  • Real-time applications


How To Import Date and Time Module :

In Python, the datetime module is used to work with dates, times, and date–time combinations. It is part of Python’s standard library, so no installation is required.

You can import it in different ways depending on your need.
import datetime

Get Current Date and Time:

This code obtains the current system date and time as a single datetime object using the datetime module.

Example:
import datetime now = datetime.datetime.now() print(now)

Output:
2026-02-13 11:25:53.445827

"Code executed successfully" 

Get Only Date:

This code retrieves the current date from the system using the datetime module.

Example:
import datetime today = datetime.date.today() print(today)

Output:
2026-02-13

"Code executed successfully" 

Get Only Time:

This code retrieves only the current time (hours, minutes, and seconds) from the system using the datetime module.

Example:
import datetime time = datetime.datetime.now().time() print(time)


Output:
11:18:31.974124

"Code executed successfully" 

Create a Specific Date:

This code creates a date object representing a specific calendar date using the datetime module.

Example:
import datetime d = datetime.date(2026, 1, 22) print(d)


Output:
2026-01-22

"Code executed successfully" 

Create Date & Time Together:

This code creates a datetime object that combines a specific date and time into a single value.

Example:
import datetime dt = datetime.datetime(2026, 1, 22, 10, 30) print(dt)

Output:
2026-01-22 10:30:00

"Code executed successfully" 

Extract Date Components:

This code gets the current date and time and formats it into a readable date (DD-MM-YYYY) and time (HH:MM:SS) using strftime().

Example:
import datetime now = datetime.datetime.now() print(now.year) print(now.month) print(now.day) print(now.hour) print(now.minute)

Output:
2026 2 13 11 1

"Code executed successfully" 

Format Date & Time (strftime()):

strftime() is used to format a date or time object into a readable string according to a specified format.

Example:
import datetime now = datetime.datetime.now() print(now.strftime("%d-%m-%Y")) print(now.strftime("%H:%M:%S"))

Output:
13-02-2026 11:05:18

"Code executed successfully" 

Common Format Codes:

Code                       Meaning
 %dDay
%mMonth
%YYear
%HHour
%MMinute
%SSecond

Convert String to Date (strptime()):

strptime() is used to convert a date given as a string into a datetime object by specifying the correct date format.

Example:
import datetime date_str = "22-01-2026" date_obj = datetime.datetime.strptime(date_str, "%d-%m-%Y") print(date_obj)


Output:
2026-01-22 00:00:00

"Code executed successfully" 

Time Difference (timedelta):

timedelta represents the difference between two dates or times, and it is used to calculate the number of days, seconds, or other time intervals between them.

Example:
import datetime d1 = datetime.date(2026, 1, 1) d2 = datetime.date(2026, 1, 10) diff = d2 - d1 print(diff.days)


Output:
9

"Code executed successfully" 


Add or Subtract Days:

This code uses timedelta to add or subtract a specific number of days from a given date.

Example:
from datetime import timedelta, date today = date.today() new_date = today + timedelta(days=5) print(new_date)


Output:
2026-02-18

"Code executed successfully" 

Get Weekday:

This code returns the weekday number of the current date, where Monday is 0 and Sunday is 6.

Example:
today = datetime.date.today() print(today.weekday()) # Monday = 0

Output:
4

"Code executed successfully" 

Real-Life Example: Expiry Check.

Example:
import datetime expiry = datetime.date(2026, 2, 1) today = datetime.date.today() if today > expiry: print("Expired") else: print("Valid")

Output:
Expired

"Code executed successfully" 

❌ Common Mistakes

  • Forgetting to import datetime

  • Confusing date and datetime

  • Wrong format codes


Interview Questions ?

1️⃣ Difference between date and datetime ?

Ans:
date stores only the calendar date (year, month, day), while datetime stores both date and time (year, month, day, hour, minute, second).

2️⃣ What is timedelta?

Ans:
timedelta represents the difference between two dates or times and is used for date and time calculations.

3️⃣ Use of strftime()?

Ans:

strftime() is used to format date and time objects into readable string representations using specified format codes.


Conclusion :

Python date and time handling is essential for real-world applications.
Mastering it helps in data processing, automation, and analytics.


💬 Quick Question

What will be the output?

import datetime print(datetime.date.today().year)

Comment your answer 👇😊


📌 Related Articles

Comments

popular

What Is Python Programming? Features, Uses and Career Scope.

  ✍️ Introduction Python is one of the most popular and beginner-friendly programming languages in the world today. It is widely used for web development, data science, artificial intelligence, automation, and software development. Because of its simple syntax and powerful features, Python is an excellent choice for students, beginners, and professionals. In this article, you will learn what Python programming is, its key features, real-life uses, and the career opportunities it offers. 🧠 What Is Python Programming? Python is a high-level, interpreted programming language created to make coding easy and readable. It allows developers to write programs using simple English-like statements, which makes it ideal for beginners. Python supports multiple programming styles such as procedural, object-oriented, and functional programming. ⭐ Features of Python Easy to learn and understand Simple and readable syntax Interpreted language Platform independent Large standard l...

Features of Python Programming Language Explained with Examples

✍️ Introduction Python is one of the most popular programming languages because of its powerful and easy-to-use features. It is designed to make programming simple, readable, and efficient. Python is widely used by beginners as well as professionals due to its flexibility and strong community support. In this article, we will discuss the main features of Python programming language in simple English with easy examples. 🧠 What Are Features of Python? Features of Python are the special characteristics that make it different from other programming languages. These features help programmers write clean, readable, and efficient code with less effort. ⭐ Key Features of Python Programming Language 1️⃣ Easy to Learn and Easy to Use Python has a simple syntax that is close to the English language. This makes it very easy for beginners to learn and understand programming concepts. Example: print("Hello, World!") 2️⃣ Interpreted Language Python is an interpreted language, which me...

Python Operators: Types with Examples

 ✍️Introduction In Python, operators are symbols used to perform operations on variables and values. Operators help us do calculations, comparisons, and logical decisions in programs. In this article, you will learn: • What Python operators are • Types of Python operators • Simple examples for each type