Date & Time | Dataplexa

Date & Time in Python

Working with dates and times is very important in real-world applications. Python provides a powerful built-in module called datetime that helps you create, format, compare, and manipulate date and time values easily. You will use it in automation, billing systems, scheduling, logging, analytics, and many other tasks.

Importing the datetime Module

Python's datetime module contains several classes for handling date and time. We begin by importing it so we can access functions like current date, current time, formatting, and calculations.

import datetime

Getting the Current Date and Time

The now() function returns the exact date and time at the moment the code is executed. This is commonly used for timestamps, logs, and tracking when events occur.

from datetime import datetime

current = datetime.now()
print(current)

Extracting Year, Month, Day, Hour, Minute, Second

After getting the current datetime, we can extract individual components like year or hour. This is especially useful when organizing files, generating reports, or validating dates.

now = datetime.now()

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

Creating Your Own Date or Time

You can manually create date or time objects by supplying year, month, and day. This is used whenever programs need to represent a specific moment in time.

from datetime import date, time

d = date(2025, 12, 25)
t = time(14, 30, 0)

print(d)
print(t)

Formatting Date & Time (strftime)

The strftime() method converts datetime objects into readable text formats. It allows you to create custom date strings for dashboards, logs, and user interfaces.

now = datetime.now()

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

Common Formatting Codes

  • %Y – Year (2025)
  • %m – Month (01–12)
  • %d – Day (01–31)
  • %H – Hour (00–23)
  • %M – Minute (00–59)
  • %S – Second (00–59)

Converting Strings to Date (strptime)

The strptime() function takes a date string and converts it back into a datetime object. This is very useful when reading dates from files, forms, or external sources.

date_text = "2025-06-15 12:45:00"

result = datetime.strptime(date_text, "%Y-%m-%d %H:%M:%S")
print(result)

Working with Timedelta (Date Differences)

timedelta represents the difference between two dates or times. You can use it to calculate deadlines, durations, or ages.

from datetime import timedelta

today = datetime.now()
future = today + timedelta(days=10)

print("Today:", today)
print("After 10 days:", future)

Comparing Dates

Python allows comparing datetime objects directly using comparison operators. This helps in checking expiry dates, logging events, or scheduling tasks.

d1 = datetime(2025, 5, 1)
d2 = datetime(2025, 7, 1)

if d1 < d2:
    print("d1 is earlier")

📝 Practice Exercises


Exercise 1

Print the current date in the format YYYY/MM/DD.

Exercise 2

Create a datetime object representing your birthday of any year.

Exercise 3

Convert the string "2025-10-20 09:30:00" into a datetime object.

Exercise 4

Calculate the date 30 days from today using timedelta.


✅ Practice Answers


Answer 1

now = datetime.now()
print(now.strftime("%Y/%m/%d"))

Answer 2

birthday = datetime(1999, 4, 15)
print(birthday)

Answer 3

result = datetime.strptime("2025-10-20 09:30:00", "%Y-%m-%d %H:%M:%S")
print(result)

Answer 4

future = datetime.now() + timedelta(days=30)
print(future)