📅 datetime Module
Last Updated: 17th August 2025
The datetime module provides a way to work with date and time values in Python. It allows you to create, manipulate, and format date and time objects.
List of Datetime Functions:
- datetime.now(): Returns the current date and time as a datetime object.
from datetime import datetime
dt = datetime.now()
print(dt)
#Access Specific Parts of Date/Time
print(dt.year)
print(dt.month)
print(dt.day)
print(dt.hour)
print(dt.minute)
- strftime(format): Converts a datetime object to a formatted string.
from datetime import datetime
current_date = datetime.now()
formatted_date = current_date.strftime("%Y-%m-%d")
print(formatted_date)
- datetime.today(): Returns the current date as a datetime object.
from datetime import datetime
current_date = datetime.today()
print(current_date)
- datetime(year, month, day): Creates a datetime object with the specified year, month, and day.
from datetime import datetime
current_date = datetime(2025, 8, 17, 10, 30, 45)
print(current_date)
- datetime.strptime(date_string, format): Converts a string to a datetime object.
from datetime import datetime
date_str = "2025-08-17 14:35:00"
dt = datetime.datetime.strptime(date_str, "%Y-%m-%d %H:%M:%S")
print(dt)
- timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0): Creates a timedelta object(Add/Subtract Time) .
from datetime import timedelta
today = datetime.datetime.now()
next_week = today + timedelta(days=7)
print(next_week)