View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All

How to Work with datetime in Python: Formats, Functions, and Examples

Updated on 29/05/20253,663 Views

Datetime in Python is a crucial module for handling dates and times effectively. It allows programmers to create, manipulate, and format date and time data with ease. Whether you are working on logging events, scheduling tasks, or processing time-sensitive data, understanding the datetime module is essential.

In this article, we will explore the fundamentals of the datetime module. You will learn how to create date, time, and datetime objects. We will also cover retrieving the current date and time, formatting these objects into readable strings, performing arithmetic operations with dates, and much more. Each section includes clear examples to help you grasp the concepts better.

Pursue our Software Engineering courses to get hands-on experience!

What is the datetime Module?

Python includes a built-in module called datetime that allows you to work with dates and times easily. It offers several classes to represent, manipulate, and format date and time values. This module helps you handle everything from simple date calculations to complex time-based operations.

The datetime module also provides tools for parsing dates from strings and formatting date objects into readable formats. It is widely used in applications involving timestamps, scheduling, and logging.

Here is a simple example demonstrating how to create and display a date using the datetime module:

# Import the date class from the datetime module
from datetime import date

# Create a date object for December 25, 2025
christmas = date(2025, 12, 25)

# Display the date object
print("Christmas is on:", christmas)

Output:

Christmas is on: 2025-12-25

Explanation:

  • We import the date class from the datetime module, focusing on the date part only.
  • We create a date object named christmas representing December 25, 2024.
  • Printing the christmas object shows the date in the standard YYYY-MM-DD format.
  • This example highlights how straightforward it is to create and use date objects with the datetime module.

Take your skills to the next level with these top programs:

How to Import the datetime Module

To work with dates and times in Python, you first need to import the datetime module. This module contains several useful classes like date, time, and datetime. Each of these classes lets you create and manipulate specific types of date and time objects.

You can import the entire module or just the classes you need. After importing, you can create objects representing dates, times, or both combined.

Creating Date Objects: date(year, month, day)

The date class lets you create a date object with the year, month, and day. This is useful when you only want to work with calendar dates without time information.

# Import the date class from datetime module
from datetime import date

# Create a date object for April 15, 2025
my_birthday = date(2025, 4, 15)

# Print the date object
print("My birthday is on:", my_birthday)

Output:

My birthday is on: 2025-04-15

Explanation:

  • We import the date class specifically from the datetime module.
  • We create a date object called my_birthday representing April 15, 2025.
  • Printing the object shows the date in the standard YYYY-MM-DD format.
  • This class is ideal for handling date-only data without time.

Must Explore: String split() Method in Python

Creating Time Objects: time(hour, minute, second)

The time class lets you create a time object with hours, minutes, and seconds. This is useful when you want to represent time without any date attached.

# Import the time class from datetime module
from datetime import time

# Create a time object for 9:30:45 AM
meeting_time = time(9, 30, 45)

# Print the time object
print("Meeting time is at:", meeting_time)

Output:

Meeting time is at: 09:30:45

Explanation:

  • We import the time class from the datetime module.
  • We create a time object named meeting_time representing 9:30:45 AM.
  • The printed time follows the standard HH:MM:SS 24-hour format.
  • Use the time class when you only need to track hours, minutes, and seconds.

Creating Datetime Objects: datetime(year, month, day, hour, minute, second)

The datetime class combines both date and time information into one object. It allows you to work with complete timestamps.

# Import the datetime class from datetime module
from datetime import datetime

# Create a datetime object for May 10, 2025, at 14:45:30
event_datetime = datetime(2025, 5, 10, 14, 45, 30)

# Print the datetime object
print("Event datetime is:", event_datetime)

Output:

Event datetime is: 2025-05-10 14:45:30

Explanation:

  • We import the datetime class from the datetime module.
  • We create a datetime object named event_datetime for May 10, 2025, at 2:45:30 PM.
  • The printed format combines date and time as YYYY-MM-DD HH:MM:SS.
  • This class is perfect for situations that require full timestamps.

By importing the datetime module and using these classes, you can handle dates and times effectively in Python. This flexibility makes datetime ideal for a variety of applications, including logging, scheduling, and data analysis.

Also read the Strip in Python article!

Getting the Current Date and Time

Python’s datetime module allows you to retrieve the current date and time using built-in methods. These methods are simple to use and return different types of objects depending on your needs.

Let’s explore the most common ways to fetch the current date and time in Python.

Using datetime.now()

The datetime.now() method returns the current local date and time as a datetime object.

# Import the datetime class from datetime module
from datetime import datetime

# Create a datetime object for August 10, 2023, at 14:45:30
event_datetime = datetime(2023, 8, 10, 14, 45, 30)

# Print the datetime object
print("Event datetime is:", event_datetime)

Output:

Current date and time using now(): 2025-05-21 14:05:37.123456

Explanation:

  • datetime.now() returns both the current date and time.
  • The output includes microseconds.
  • This is useful when you need a full timestamp with precision.

Using datetime.today()

The datetime.today() method also returns the current local date and time. It behaves similarly to now().

# Import datetime class from the datetime module
from datetime import datetime

# Get the current date and time
current_datetime = datetime.now()

# Display the result
print("Current date and time using now():", current_datetime)

Output:

Current date and time using today(): 2025-05-21 14:05:37.123456

Explanation:

  • datetime.today() provides a datetime object just like now().
  • There is no major difference in basic usage between now() and today().
  • Internally, both fetch data from the system clock.

Using date.today()

If you only need the current date without time, use date.today(). It returns a date object.

# Import date class from the datetime module
from datetime import date

# Get the current date
current_date = date.today()

# Display the date
print("Today's date is:", current_date)

Output:

Today's date is: 2025-05-21

Explanation:

  • date.today() returns the current date with no time or time zone.
  • It is ideal for applications that do not need timestamps.

Learn about Self in Python and Break Statement in Python to write better code!

Using time() to Get Current Time

To work only with the current time (excluding the date), you can use the datetime.now().time() method.

# Import date class from the datetime module
from datetime import date

# Get the current date
current_date = date.today()

# Display the date
print("Today's date is:", current_date)

Output:

Current time is: 14:05:37.123456

Explanation:

  • datetime.now().time() extracts just the time portion from the full datetime object.
  • It includes hours, minutes, seconds, and microseconds.
  • This is useful when you only need the current time for tasks like reminders or logs.

Datetime Components and Attributes

After creating a datetime object in Python, you can easily access individual components like the year, month, day, hour, and more. These attributes allow you to extract specific parts of a date-time value for further processing.

Let’s see how to use these attributes effectively.

Accessing year, month, day, hour, minute, second, and microsecond

Python’s datetime objects store several components. You can access them directly using dot notation.

# Import datetime class from the datetime module
from datetime import datetime

# Create a sample datetime object
dt = datetime(2025, 5, 21, 14, 30, 45, 123456)

# Access and print each component
print("Year:", dt.year)
print("Month:", dt.month)
print("Day:", dt.day)
print("Hour:", dt.hour)
print("Minute:", dt.minute)
print("Second:", dt.second)
print("Microsecond:", dt.microsecond)

Output:

Year: 2025

Month: 5

Day: 21

Hour: 14

Minute: 30

Second: 45

Microsecond: 123456

Explanation:

  • dt.year returns the year as an integer (e.g., 2025).
  • dt.month gives the month number (1–12).
  • dt.day provides the day of the month.
  • dt.hour, dt.minute, dt.second return the time components.
  • dt.microsecond shows the microsecond part (up to 6 digits).
  • These attributes are useful for formatting or logic-based checks like filtering data.

Must Explore: Nested for loop in Python

Using weekday() and ISO Calendar Methods

Python’s datetime module also provides built-in methods to get the day of the week and ISO calendar values.

weekday() Method

This method returns the day of the week as an integer, where Monday is 0 and Sunday is 6.

from datetime import datetime

# Create a datetime object
dt = datetime(2025, 5, 21)

# Get the weekday
print("Weekday (0=Monday):", dt.weekday())

Output:

Weekday (0=Monday): 2

Explanation:

  • dt.weekday() returns 2, which means Wednesday.
  • Use this when you need the day index to apply business logic.

isoweekday() Method

This returns the day of the week as per ISO standards, where Monday is 1 and Sunday is 7.

from datetime import datetime

# Create a datetime object
dt = datetime(2025, 5, 21)

# Get ISO weekday
print("ISO Weekday (1=Monday):", dt.isoweekday())

Output:

ISO Weekday (1=Monday): 3

Explanation:

  • dt.isoweekday() gives 3, which represents Wednesday in ISO format.
  • This format is preferred in regions and systems that follow ISO 8601.

isocalendar() Method

This method returns a tuple containing the ISO year, ISO week number, and ISO weekday.

from datetime import datetime

# Create a datetime object
dt = datetime(2025, 5, 21)

# Get ISO calendar tuple
print("ISO Calendar:", dt.isocalendar())

Output:

ISO Calendar: (2025, 21, 3)

Explanation:

  • dt.isocalendar() returns a tuple: (ISO Year, Week Number, ISO Weekday).
  • For this date, it shows the 21st ISO week of 2025 and the day as Wednesday.

Also read the Top 43 Pattern Programs in Python to Master Loops and Recursion article!

Formatting Dates and Times in Python

When working with dates and times in Python, formatting them into readable strings is often necessary. The strftime() method from the datetime module lets you convert datetime objects into strings using specific format codes.

Let’s explore how to use strftime() to display dates and times in various formats.

Using strftime() to Format Datetime Objects

You can apply format codes with strftime() to control how the date and time appear. Below is an example showing common date and time formats.

# Import datetime class
from datetime import datetime

# Create a datetime object
dt = datetime(2025, 5, 21, 14, 30, 45)

# Format the datetime object into different readable forms
print("Full date and time:", dt.strftime("%Y-%m-%d %H:%M:%S"))
print("Date in DD/MM/YYYY format:", dt.strftime("%d/%m/%Y"))
print("Day name and month name:", dt.strftime("%A, %B %d, %Y"))
print("12-hour format with AM/PM:", dt.strftime("%I:%M %p"))
print("Week number of the year:", dt.strftime("%U"))

Output:

Full date and time: 2025-05-21 14:30:45  

Date in DD/MM/YYYY format: 21/05/2025  

Day name and month name: Wednesday, May 21, 2025  

12-hour format with AM/PM: 02:30 PM  

Week number of the year: 20

Explanation:

  • dt.strftime("%Y-%m-%d %H:%M:%S"): Formats to YYYY-MM-DD HH:MM:SS.
  • "%d/%m/%Y": Converts the date to day/month/year.
  • "%A, %B %d, %Y": Displays the full weekday and month names (like "Wednesday, May 21, 2025").
  • "%I:%M %p": Formats time in 12-hour format with AM or PM.
  • "%U": Returns the week number of the year (Sunday as the first day of the week).

Common Format Codes for strftime()

Here are some useful codes you can use:

Code

Meaning

Example

%Y

Four-digit year

2025

%m

Month (01 to 12)

05

%d

Day of the month

21

%H

Hour (00 to 23)

14

%I

Hour (01 to 12)

02

%p

AM/PM

PM

%M

Minutes

30

%S

Seconds

45

%A

Full weekday name

Wednesday

%B

Full month name

May

%U

Week number (Sunday 1st)

20

By using strftime(), you can easily customize how dates and times are displayed in your Python programs. This is especially useful for creating readable logs, reports, or UI elements where proper formatting matters.

Datetime Arithmetic with timedelta in Python

Python allows you to perform arithmetic operations on date and time objects using the timedelta class. This feature is useful when calculating future or past dates, or when finding the time difference between two dates.

Let’s explore how timedelta works and how you can use it to add, subtract, and compare dates and times.

What is timedelta?

The timedelta class is part of the datetime module. It represents the difference between two datetime, date, or time objects. You can define a timedelta by specifying days, seconds, microseconds, or even weeks.

Example 1: Creating and Adding a timedelta

from datetime import datetime, timedelta

# Create a datetime object for today's date
today = datetime.now()

# Create a timedelta of 5 days
delta = timedelta(days=5)

# Add timedelta to the current date
future_date = today + delta

# Print the results
print("Today:", today)
print("5 days later:", future_date)

Output:

Today: 2025-05-21 14:00:00 (varies)

5 days later: 2025-05-26 14:00:00

Explanation:

  • datetime.now() returns the current date and time.
  • timedelta(days=5) creates a time span of 5 days.
  • Adding the timedelta to the current date shifts the result forward by 5 days.

Example 2: Subtracting Dates and Times

You can subtract a timedelta to get a past date or subtract two datetime objects to find the difference.

from datetime import datetime, timedelta

# Define a specific date
event_date = datetime(2025, 6, 1)

# Create a timedelta of 10 days
delta = timedelta(days=10)

# Get the date 10 days before the event
reminder_date = event_date - delta

print("Event Date:", event_date)
print("Reminder Date:", reminder_date)

Output:

Event Date: 2025-06-01 00:00:00  

Reminder Date: 2025-05-22 00:00:00

Explanation:

  • Subtracting timedelta(days=10) from a future date gives the date 10 days earlier.
  • This is useful for scheduling reminders or deadlines.

Example 3: Calculating Differences Between Dates

You can find the duration between two datetime objects directly.

from datetime import datetime

# Define two dates
start_date = datetime(2025, 5, 1)
end_date = datetime(2025, 5, 21)

# Subtract to get the difference
difference = end_date - start_date

print("Days between:", difference.days)

Output:

Days between: 20

Explanation:

  • Subtracting two datetime objects gives a timedelta object.
  • You can access .days to get the total number of days.

Handling Timestamps in Python

Timestamps play a crucial role in many real-world applications. They represent the number of seconds that have passed since a specific point in time — known as the Unix epoch (January 1, 1970, 00:00:00 UTC). Python's datetime module makes it easy to convert between timestamps and datetime objects.

Let’s now understand what a timestamp is and how to convert between timestamps and datetime objects using built-in methods.

What is a Timestamp?

A timestamp is a numeric value that counts the total seconds (including fractions) since the Unix epoch. It helps in storing, comparing, and processing time values efficiently, especially in databases, logs, or APIs.

Converting datetime Objects to Timestamps

To get a timestamp from a datetime object, you can use the timestamp() method. But make sure the datetime object is timezone-aware if needed.

from datetime import datetime

# Create a datetime object
dt = datetime(2025, 5, 21, 14, 30, 0)

# Convert to timestamp
ts = dt.timestamp()

print("Datetime:", dt)
print("Timestamp:", ts)

Output:

Datetime: 2025-05-21 14:30:00  

Timestamp: 1747847400.0

Explanation:

  • datetime(2025, 5, 21, 14, 30, 0) creates a specific date and time.
  • .timestamp() converts this datetime into seconds since the epoch.
  • The result is a float where decimals represent microseconds.

Converting Timestamps to datetime Objects

To reverse the process, use the fromtimestamp() method. It converts a numeric timestamp into a datetime object.

from datetime import datetime

# Define a timestamp
ts = 1747847400.0

# Convert to datetime
dt = datetime.fromtimestamp(ts)

print("Timestamp:", ts)
print("Converted datetime:", dt)

Output:

Timestamp: 1747847400.0  

Converted datetime: 2025-05-21 14:30:00

Explanation:

  • The fromtimestamp() method takes a float or integer timestamp.
  • It returns a datetime object that represents the same point in time.

Also explore Python's do-while Loop article!

Advanced Datetime Operations in Python

The datetime module in Python goes beyond basic date and time handling. It allows advanced operations such as modifying specific parts of a date, comparing datetime objects, and formatting in ISO 8601 standards.

These features are helpful in scheduling systems, log analysis, API integrations, and more.

Replacing Parts of datetime Objects (Using replace() Method)

You can modify specific components of a datetime object without creating a new one from scratch. The replace() method makes this easy.

from datetime import datetime

# Original datetime object
dt = datetime(2025, 5, 21, 14, 30)

# Replace hour and minute
updated_dt = dt.replace(hour=9, minute=0)

print("Original datetime:", dt)
print("Updated datetime:", updated_dt)

Output:

Original datetime: 2025-05-21 14:30:00  

Updated datetime: 2025-05-21 09:00:00

Explanation:

  • replace(hour=9, minute=0) keeps the date the same but changes the time to 9:00 AM.
  • This method is useful when adjusting only parts of a date or time, like setting start or end hours.

Must Read: Break Pass and Continue Statement in Python

Comparing datetime Objects

Python supports comparison operators (<, >, ==, etc.) for datetime objects. This is useful when you want to check if one date occurs before or after another.

from datetime import datetime

dt1 = datetime(2025, 5, 21, 10, 0)
dt2 = datetime(2025, 5, 21, 12, 0)

# Compare two datetime objects
print("dt1 is earlier than dt2:", dt1 < dt2)
print("dt1 equals dt2:", dt1 == dt2)

Output:

dt1 is earlier than dt2: True  

dt1 equals dt2: False

Explanation:

  • dt1 < dt2 checks if dt1 comes before dt2.
  • You can also use >=, !=, and other standard operators.

Working with ISO 8601 Format Dates

The ISO 8601 format is an international standard for representing date and time. Python supports this format through isoformat() and fromisoformat() methods.

Convert to ISO 8601 String

from datetime import datetime

dt = datetime(2025, 5, 21, 14, 30)

# Convert datetime to ISO 8601 format
iso_string = dt.isoformat()

print("ISO 8601 format:", iso_string)

Output:

ISO 8601 format: 2025-05-21T14:30:00

Convert from ISO 8601 String

from datetime import datetime

iso_string = "2025-05-21T14:30:00"

# Parse ISO 8601 string back to datetime
parsed_dt = datetime.fromisoformat(iso_string)

print("Parsed datetime:", parsed_dt)

Output:

Parsed datetime: 2025-05-21 14:30:00

Explanation:

  • isoformat() is ideal when sharing data with APIs or external systems.
  • fromisoformat() simplifies converting strings into usable datetime objects.

Also read the Reverse String in Python article!

Conclusion

Understanding datetime in Python is essential for anyone working with time-sensitive data. The datetime module offers powerful tools to create, manipulate, format, and compare date and time values. With clear methods and flexible functionality, it allows developers to manage temporal data efficiently.

By applying these concepts, you can write Python programs that handle real-world scheduling, logging, event tracking, and data comparison tasks. The key is to choose the right method for your specific use case and maintain clarity in your code. Keep practicing, and soon working with dates and times in Python will feel seamless and intuitive.

FAQs

1. Can I use datetime in Python to schedule recurring tasks?

Yes, you can use datetime in Python to calculate recurring intervals like daily or weekly events. However, scheduling itself isn’t handled by datetime alone. For recurring execution, you should pair it with libraries like schedule or APScheduler.

2. What is the difference between naive and aware datetime objects?

A naive datetime object doesn’t contain timezone information. An aware datetime object includes timezone data using the tzinfo attribute. This distinction becomes crucial when working across different time zones or during daylight saving time changes.

3. How does datetime in Python handle leap years?

Python’s datetime module automatically accounts for leap years when working with dates. If you try to create an invalid date like February 29 on a non-leap year, it will raise a ValueError, ensuring date accuracy.

4. Can you compare a date object with a datetime object in Python?

Direct comparison between date and datetime objects will raise a TypeError. To compare them, you should first convert the datetime object to a date using .date() or convert the date to datetime using datetime.combine().

5. How can I convert a datetime object to a string and back?

To convert a datetime object to a string, use strftime(). To convert the string back to a datetime object, use strptime(). This is useful for saving, sharing, or logging date and time values in readable formats.

6. Is it possible to sort a list of datetime objects in Python?

Yes, you can sort a list of datetime objects using Python’s built-in sorted() function or the .sort() method. These objects are comparable, and Python sorts them in chronological order automatically based on date and time.

7. Does the datetime module support localization?

The datetime module itself doesn’t support locale-specific formatting, but it can be combined with the locale module or third-party libraries like babel to display localized date formats, names of days, and months in various languages.

8. What’s the best way to measure time differences in Python?

To measure time differences accurately, use datetime and timedelta. For high-precision timing (like benchmarking code), use the timeit or perf_counter() from the time module instead of datetime.

9. How do I find the number of days between two dates using datetime in Python?

To find the difference in days, subtract two date or datetime objects. This returns a timedelta object. Then, use the .days attribute to get the exact number of days between the two dates.

10. Can I create custom datetime formats for input parsing?

Yes, you can define custom formats for parsing strings into datetime objects using strptime(). You must provide the exact format pattern using format codes like %d, %m, %Y, etc., to match your input string correctly.

11. How is datetime in Python different from time and calendar modules?

While datetime offers classes for date, time, and combined values, the time module focuses more on UNIX timestamps and delays. The calendar module is ideal for month/year calculations. Each has its use, but datetime is the most versatile for everyday date-time handling.

image

Take our Free Quiz on Python

Answer quick questions and assess your Python knowledge

right-top-arrow
image
Join 10M+ Learners & Transform Your Career
Learn on a personalised AI-powered platform that offers best-in-class content, live sessions & mentorship from leading industry experts.
advertise-arrow

Free Courses

Explore Our Free Software Tutorials

upGrad Learner Support

Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)

text

Indian Nationals

1800 210 2020

text

Foreign Nationals

+918068792934

Disclaimer

1.The above statistics depend on various factors and individual results may vary. Past performance is no guarantee of future results.

2.The student assumes full responsibility for all expenses associated with visas, travel, & related costs. upGrad does not provide any a.