Python provides the built-in datetime module to work with dates and times. It allows developers to create, display, compare, format, and manipulate dates and times in Python programs. The datetime module provides classes such as date, time, datetime, and timedelta for handling different date and time operations.
Table of Contents
What are Date and Time in Python?
Date and time represent information about a particular day and time. Python provides the datetime module to work with this information.
The main classes provided by the module are:
| Class | Description |
|---|---|
| date | Represents a date such as year, month, and day |
| time | Represents time such as hour, minute, second, and microsecond |
| datetime | Represents both date and time |
| timedelta | Represents a duration or difference between dates and times |
Why Use Date and Time in Python?
Date and time operations are useful in many Python applications. They help programs work with dates, times, schedules, and time-based information.
- Display the Current Date and Time: Python can be used to display the current date and time whenever an application needs this information.
- Compare Dates: Date and time functionality allows programs to compare two dates and determine which one comes earlier or later.
- Calculate Date Differences: Python can calculate the difference between two dates, such as the number of days between them.
- Format Dates: Dates can be formatted into different readable forms to suit the requirements of an application.
- Parse Date Strings: Python can convert date strings into date objects, making them easier to work with in programs.
- Handle Scheduling and Time-Based Operations: Date and time functionality is useful for scheduling tasks and performing operations based on specific dates or times.
- Work with Logs, Reports, and Databases: Date and time values are commonly used in logs, reports, and databases to record when events or activities occur.
Importing the datetime Module
The datetime module is part of Python's standard library, so it does not need to be installed separately. It can be imported using:
import datetime
Example:
# Python program to import the datetime module import datetime print(datetime.date.today())
Output:
2026-09-23
The output date depends on the day when the program is executed.
Getting the Current Date
The date.today() method returns the current local date.
# Python program to get the current date from datetime import date today = date.today() print(today)
Output:
2026-09-23
The output changes according to the current date.
Getting the Current Time
The datetime.now() method can be used to get the current local date and time. The time portion can then be extracted using .time().
# Python program to get the current time from datetime import datetime current_time = datetime.now().time() print(current_time)
Output:
10:30:45.123456
The exact output depends on the time when the program is executed.
Getting the Current Date and Time
The datetime.now() method returns the current local date and time.
# Python program to get the current date and time from datetime import datetime current_datetime = datetime.now() print(current_datetime)
Output:
2026-09-23 10:30:45.123456
The exact output depends on when the program is executed.
Creating a Specific Date
The date() class can be used to create a specific date.
Syntax:
date(year, month, day)
Example:
# Python program to create a specific date from datetime import date birthday = date(2004, 5, 15) print(birthday)
Output:
2004-05-15
Creating a Specific Time
The time() class can be used to create a specific time.
Syntax:
time(hour, minute, second)
Example:
# Python program to create a specific time from datetime import time meeting_time = time(10, 30, 0) print(meeting_time)
Output:
10:30:00
Formatting Date and Time
The strftime() method is used to convert a date or time object into a formatted string.
Some commonly used format codes are:
| Code | Meaning |
|---|---|
| %Y | Four-digit year |
| %m | Month as a number |
| %d | Day of the month |
| %H | Hour in 24-hour format |
| %M | Minute |
| %S | Second |
| %A | Full weekday name |
| %B | Full month name |
Example:
# Python program to format a date and time
from datetime import datetime
current_datetime = datetime.now()
formatted_date = current_datetime.strftime("%d-%m-%Y")
print(formatted_date)
Output:
23-09-2026
The output depends on the current date.
Extracting Date and Time Components
Individual components such as year, month, day, hour, minute, and second can be accessed from a datetime object.
# Python program to extract date and time components from datetime import datetime current_datetime = datetime.now() print(current_datetime.year) print(current_datetime.month) print(current_datetime.day) print(current_datetime.hour) print(current_datetime.minute)
Output:
2026
9
23
10
30
The hour and minute depend on the time when the program is executed.
Comparing Dates and Times
Date and time objects can be compared using comparison operators such as >, <, ==, >=, and <=.
# Python program to compare two dates
from datetime import date
date1 = date(2026, 9, 20)
date2 = date(2026, 9, 25)
if date1 < date2:
print("date1 is earlier than date2")
Output:
date1 is earlier than date2
Using timedelta
The timedelta class represents a duration or difference between dates and times.
It can be used to add or subtract days, weeks, hours, minutes, and other time units.
# Python program to use timedelta with dates from datetime import date, timedelta today = date(2026, 9, 23) future_date = today + timedelta(days=7) print(future_date)
Output:
2026-09-30
Here, seven days are added to the given date.
Parsing a Date String
The strptime() method converts a string into a datetime object according to a specified format.
Syntax:
datetime.strptime(date_string, format)
Example:
# Python program to convert a date string into a datetime object from datetime import datetime date_string = "23-09-2026" date_object = datetime.strptime(date_string, "%d-%m-%Y") print(date_object)
Output:
2026-09-23 00:00:00
The format passed to strptime() must match the format of the input string.
Advantages of Date and Time in Python
- Easy Date Handling: Python provides classes specifically designed for date and time operations
- Date Calculations: timedelta makes it easy to add or subtract time periods.
- Formatting Support: strftime() allows dates and times to be displayed in different formats.
- String Conversion: strptime() can convert formatted strings into datetime objects.
- Comparison: Date and time objects can be compared directly.
- Built-in Module: The datetime module is included with Python and requires no separate installation.
Common Beginner Mistakes
- Confusing date and datetime: The date class represents only a date, while datetime represents both a date and a time.
- Using the Wrong Format Codes: Make sure the format codes used with strftime() and strptime() match the required date or time format.
- Forgetting to Import the Required Class: When using from datetime import date, datetime, or timedelta, make sure the required class has been imported.
- Treating Date Strings as Date Objects: A date stored as a string cannot be directly used for all date calculations. Convert it into a date or datetime object when necessary.
- Assuming the Current Date or Time Is Fixed: Functions such as date.today() and datetime. now () return values based on the time when the program is executed.
Conclusion
Python provides the datetime module for working with dates, times, and durations. Classes such as date, time, datetime, and timedelta make it easy to create, format, compare, and manipulate date and time values. Methods such as strftime() and strptime() are useful for formatting and converting date strings. These features make Python suitable for applications that require scheduling, reporting, logging, and other time-based operations.
Frequently Asked Questions
1. Which module is used to work with date and time in Python?
The built-in datetime module is used to work with dates, times, and durations in Python.
2. How can you get the current date in Python?
The date.today() method can be used to get the current local date.
3. Which method is used to format a date and time?
The strftime() method is used to format a date or time object into a string.
4. What is the purpose of timedelta?
timedelta represents a duration and can be used to add or subtract periods from date and time objects.
5. What is the difference between strftime() and strptime()?
strftime() converts a date or time object into a formatted string, while strptime() converts a formatted string into a datetime object.
0 Comments