Date and Time in Python

Time is everywhere in our lifeβ€”whether it’s checking the current time, scheduling a meeting, or calculating someone’s age. Python provides powerful tools to work with dates and times, mainly through the datetime module.

Date and Time in Python

In this post, we’ll go step by step from basics to advanced concepts with real-life examples.


1. Importing datetime Module

Python’s datetime module is the main toolkit for working with dates and times.

import datetime

2. Getting Current Date and Time

You can get the current local date and time with:

import datetime

now = datetime.datetime.now()
print("Current Date and Time:", now)

πŸ‘‰ Example Output:

Current Date and Time: 2025-08-17 14:45:30.123456
  • now() gives you both date and time.
  • today() also works the same as now().

3. Getting Only Date or Only Time

Sometimes, you only need the date or time separately.

import datetime

today = datetime.date.today()
print("Today's Date:", today)

time_now = datetime.datetime.now().time()
print("Current Time:", time_now)

πŸ‘‰ Example Output:

Today's Date: 2025-08-17
Current Time: 14:45:30.123456

4. Accessing Year, Month, Day, Hour, Minute, Second

You can extract individual parts easily:

now = datetime.datetime.now()
print("Year:", now.year)
print("Month:", now.month)
print("Day:", now.day)
print("Hour:", now.hour)
print("Minute:", now.minute)
print("Second:", now.second)

5. Formatting Dates and Times (strftime)

Python allows formatting of date and time into human-readable strings.

now = datetime.datetime.now()
formatted = now.strftime("%d-%m-%Y %H:%M:%S")
print("Formatted Date & Time:", formatted)

πŸ‘‰ Common Format Codes:

  • %d β†’ Day
  • %m β†’ Month
  • %Y β†’ Year
  • %H β†’ Hour (24-hour format)
  • %M β†’ Minute
  • %S β†’ Second

πŸ‘‰ Output:

Formatted Date & Time: 17-08-2025 14:45:30

6. Parsing Strings into Date (strptime)

What if you have a date as a string? You can convert it into a datetime object:

date_string = "25-12-2025 10:30:00"
dt_object = datetime.datetime.strptime(date_string, "%d-%m-%Y %H:%M:%S")
print("Converted Date Object:", dt_object)

πŸ‘‰ Output:

Converted Date Object: 2025-12-25 10:30:00
  • strftime() β†’ Stands for String Format Time. It converts a datetime object into a string (for displaying in a custom format).
  • strptime() β†’ Stands for String Parse Time. It converts a string into a datetime object (for processing dates in Python).

πŸ‘‰ Easy way to remember: f = format (object β†’ string), p = parse (string β†’ object).


7. Timedelta (Working with Date Differences)

timedelta is used for date arithmetic (like yesterday, tomorrow, age calculation, etc.).

import datetime

today = datetime.date.today()
yesterday = today - datetime.timedelta(days=1)
tomorrow = today + datetime.timedelta(days=1)

print("Yesterday:", yesterday)
print("Tomorrow:", tomorrow)

πŸ‘‰ Example Output:

Yesterday: 2025-08-16
Tomorrow: 2025-08-18

Read More: File Handling in Python


Example: Age Calculator

import datetime

dob = datetime.date(1998, 5, 10)   # Date of Birth
today = datetime.date.today()

age = today.year - dob.year - ((today.month, today.day) < (dob.month, dob.day))
print("Your Age is:", age)

πŸ‘‰ Output:

Your Age is: 27

Explaination of below code:

age = today.year - dob.year - ((today.month, today.day) < (dob.month, dob.day))

today.year – dob.year β†’ This gives the difference between the current year and the birth year

((today.month, today.day) < (dob.month, dob.day)) β†’ This checks whether the person’s birthday has already occurred this year or not.

If the birthday hasn’t come yet, it returns True (which is 1 in Python).

If the birthday has already passed, it returns False (which is 0).

Subtracting this result ensures the age is calculated correctly.

Example:

Today = 17-08-2025

Date of Birth = 20-09-2000

Here, the birthday (20 Sept) hasn’t come yet in 2025 β†’ condition is True β†’ subtract 1.
So, 2025 – 2000 – 1 = 24 years old.


8. Working with Timezones (pytz)

Python’s datetime doesn’t handle timezones by itself. For that, use pytz.

import datetime
import pytz

utc_time = datetime.datetime.now(pytz.utc)
print("UTC Time:", utc_time)

india_time = utc_time.astimezone(pytz.timezone("Asia/Kolkata"))
print("Indian Time:", india_time)

πŸ‘‰ Example Output:

UTC Time: 2025-08-17 09:15:30.123456+00:00
Indian Time: 2025-08-17 14:45:30.123456+05:30

9. Measuring Execution Time

You can also calculate how long a program takes to run.

import datetime
import time

start = datetime.datetime.now()

# some task
time.sleep(2)

end = datetime.datetime.now()
print("Execution Time:", end - start)

πŸ‘‰ Output:

Execution Time: 0:00:02.000123

10. Real-Life Example: Reminder App

import datetime
import time

reminder_time = datetime.datetime.strptime("17-08-2025 15:00:00", "%d-%m-%Y %H:%M:%S")

print("Reminder set for:", reminder_time)

while True:
    if datetime.datetime.now() >= reminder_time:
        print("πŸ”” Time to attend the meeting!")
        break
    time.sleep(1)

πŸ‘‰ Output:

Reminder set for: 2025-08-17 15:00:00
πŸ”” Time to attend the meeting!

Final Thoughts

  • Use datetime.now() to get current date and time.
  • Use strftime() and strptime() for formatting and parsing.
  • Use timedelta for calculations (like age, deadlines, schedules).
  • Use pytz for handling multiple timezones.

Mastering date and time in Python is essential for real-world applications like logging, scheduling, reminders, file management, and automation.

FAQs – Date and Time in Python

  • datetime.date β†’ Stores only the date (year, month, day).

  • datetime.time β†’ Stores only the time (hour, minute, second, microsecond).

  • datetime.datetime β†’ Stores both date and time together.

Use strftime(). For example:

from datetime import datetime
now = datetime.now()
print(now.strftime("%d-%m-%Y"))

This prints the date in DD-MM-YYYY format.

Use strptime(). For example:

from datetime import datetime
date_str = "17-08-2025"
date_obj = datetime.strptime(date_str, "%d-%m-%Y")
print(date_obj)

Yes! You can use timedelta. For example:

from datetime import datetime, timedelta
today = datetime.now()
future = today + timedelta(days=7)
print(future)

This will give the date 7 days from today.

Spread the love

Leave a Comment

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

Translate Β»
Scroll to Top