Python
Python

 

 

🔍 Introduction

Working with date and time is essential in most real-world applications, such as logging events, scheduling tasks, or building time-based functionality. Python’s built-in datetime module provides a robust set of functions to handle dates and times effortlessly.

🎯 Objective

The objective of this tutorial is to demonstrate how to:

  • Get the current date and time
  • Format dates and times
  • Calculate time differences
  • Work with timedeltas (date/time arithmetic)

💻 Python Code Example


import datetime

# Get current date and time
now = datetime.datetime.now()
print(“Current Date and Time:”, now)

# Format date
formatted_date = now.strftime(“%A, %d %B %Y %I:%M:%S %p”)
print(“Formatted Date:”, formatted_date)

# Create a specific date
custom_date = datetime.datetime(2024, 12, 25, 10, 30)
print(“Custom Date:”, custom_date)

# Time difference between now and custom date
time_diff = custom_date – now
print(“Time until Custom Date:”, time_diff)

# Add 7 days to current date
week_later = now + datetime.timedelta(days=7)
print(“Date One Week from Now:”, week_later)

🧠 Explanation of the Program

Here’s how the program works:

  • datetime.datetime.now() fetches the current local date and time.
  • strftime() formats the datetime object into a readable string.
  • datetime.datetime() creates a custom date object (like a future event).
  • Subtracting two datetime objects gives a timedelta, which shows the time difference.
  • datetime.timedelta(days=7) is used to add (or subtract) days from a date.

🚀 How to Run the Program

  1. Make sure you have Python installed (version 3.6+ is recommended).
  2. Open your favorite text editor or IDE (such as VS Code, PyCharm, or even Notepad).
  3. Copy and paste the code into a new file and save it as datetime_demo.py.
  4. Open a terminal or command prompt, navigate to the file location, and run:
    python datetime_demo.py
© 2025 Learn Programming. All rights reserved.

 

By Aditya Bhuyan

I work as a cloud specialist. In addition to being an architect and SRE specialist, I work as a cloud engineer and developer. I have assisted my clients in converting their antiquated programmes into contemporary microservices that operate on various cloud computing platforms such as AWS, GCP, Azure, or VMware Tanzu, as well as orchestration systems such as Docker Swarm or Kubernetes. For over twenty years, I have been employed in the IT sector as a Java developer, J2EE architect, scrum master, and instructor. I write about Cloud Native and Cloud often. Bangalore, India is where my family and I call home. I maintain my physical and mental fitness by doing a lot of yoga and meditation.

Leave a Reply

Your email address will not be published. Required fields are marked *

error

Enjoy this blog? Please spread the word :)