In Python, the datetime module provides classes for manipulating dates and times. It offers several functions and methods to create, manipulate, and format…
Author
SQLDataDev Editorial Team
Mar 19, 2026 3 min read
In Python, the datetime module provides classes for manipulating dates and times. It offers several functions and methods to create, manipulate, and format date and time objects.
C++
import datetime
Classes in the datetime Module
datetime.date: Represents a date (year, month, day).
datetime.time: Represents a time (hour, minute, second, microsecond).
datetime.datetime: Represents both date and time.
datetime.timedelta: Represents the difference between two dates or times.
datetime.tzinfo: An abstract base class for dealing with time zones.
Creating Date and Time Objects
PHP
# Creating a date object
date_obj = datetime.date(2023, 6, 4)
print(date_obj) # Output: 2023-06-04# Creating a time object
time_obj = datetime.time(14, 30, 45)
print(time_obj) # Output: 14:30:45# Creating a datetime object
datetime_obj = datetime.datetime(2023, 6, 4, 14, 30, 45)
print(datetime_obj) # Output: 2023-06-04 14:30:45
Methods and Functions
SQL
# today(), now(), and utcnow() Methods
# Currentlocaldatecurrent_date= datetime.date.today()
print(current_date) # Output: currentdatein YYYY-MM-DD
# Currentlocaldateandtime
current_datetime = datetime.datetime.now()
print(current_datetime) # Output: currentdateandtimein YYYY-MM-DD HH:MM:SS
# Current UTC dateandtime
current_utc_datetime = datetime.datetime.utcnow()
print(current_utc_datetime) # Output: current UTC dateandtimein YYYY-MM-DD HH:MM:SS
PHP
# Creating a timedelta object
delta = datetime.timedelta(days=10, hours=5, minutes=30)
print(delta) # Output: 10 days, 5:30:00# Adding timedelta to a datetime object
future_date = datetime.datetime.now() + delta
print(future_date) # Output: current date and time + 10 days, 5 hours, 30 minutes
PHP
# Formatting a datetime object to a string
formatted_date = datetime_obj.strftime("%Y-%m-%d %H:%M:%S")
print(formatted_date) # Output: 2023-06-04 14:30:45# Parsing a string to a datetime object
parsed_date = datetime.datetime.strptime("2023-06-04 14:30:45", "%Y-%m-%d %H:%M:%S")
print(parsed_date) # Output: 2023-06-04 14:30:45