For working professionals
For fresh graduates
More
13. Print In Python
15. Python for Loop
19. Break in Python
23. Float in Python
25. List in Python
27. Tuples in Python
29. Set in Python
53. Python Modules
57. Python Packages
59. Class in Python
61. Object in Python
73. JSON Python
79. Python Threading
84. Map in Python
85. Filter in Python
86. Eval in Python
96. Sort in Python
101. Datetime Python
103. 2D Array in Python
104. Abs in Python
105. Advantages of Python
107. Append in Python
110. Assert in Python
113. Bool in Python
115. chr in Python
118. Count in python
119. Counter in Python
121. Datetime in Python
122. Extend in Python
123. F-string in Python
125. Format in Python
131. Index in Python
132. Interface in Python
134. Isalpha in Python
136. Iterator in Python
137. Join in Python
140. Literals in Python
141. Matplotlib
144. Modulus in Python
147. OpenCV Python
149. ord in Python
150. Palindrome in Python
151. Pass in Python
156. Python Arrays
158. Python Frameworks
160. Python IDE
164. Python PIP
165. Python Seaborn
166. Python Slicing
168. Queue in Python
169. Replace in Python
173. Stack in Python
174. scikit-learn
175. Selenium with Python
176. Self in Python
177. Sleep in Python
179. Split in Python
184. Strip in Python
185. Subprocess in Python
186. Substring in Python
195. What is Pygame
197. XOR in Python
198. Yield in Python
199. Zip in Python
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!
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:
Take your skills to the next level with these top programs:
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.
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:
Must Explore: String split() Method in Python
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:
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:
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!
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.
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:
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:
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:
Learn about Self in Python and Break Statement in Python to write better code!
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:
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.
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:
Must Explore: Nested for loop in Python
Python’s datetime module also provides built-in methods to get the day of the week and ISO calendar values.
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:
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:
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:
Also read the Top 43 Pattern Programs in Python to Master Loops and Recursion article!
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.
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:
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.
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.
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:
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:
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:
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.
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.
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:
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:
Also explore Python's do-while Loop article!
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.
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:
Must Read: Break Pass and Continue Statement in Python
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:
The ISO 8601 format is an international standard for representing date and time. Python supports this format through isoformat() and fromisoformat() methods.
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
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:
Also read the Reverse String in Python article!
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.
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.
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.
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.
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().
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.
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.
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.
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.
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.
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.
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.
Take our Free Quiz on Python
Answer quick questions and assess your Python knowledge
Author|900 articles published
Previous
Next
Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)
Indian Nationals
1800 210 2020
Foreign Nationals
+918068792934
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.