Introduction to Python Datetime
Python Datetime
The datetime
module provides classes and functions for working with dates, times, and time intervals.
It allows you to manipulate and format dates and times, perform calculations, and extract information from them.
Here's an overview of how to work with dates and times using the datetime module:
Importing the datetime Module
Before using the datetime module, you need to import it.
Date Creation
The datetime
module provides the date
class for working with dates. You can create a date object using the date()
constructor, specifying the year, month, and day.
my_date = datetime.date(2022, 3, 15)
You can also create date objects for the current date using the today()
method:
today = datetime.date.today()
Time Creation
The datetime
module provides the time
class for working with times.
You can create a time object using the time()
constructor, specifying the hour, minute, second, and microsecond.
my_time = datetime.time(9, 30, 45)
You can also create time objects for the current time using the now()
method:
current_time = datetime.datetime.now().time()
Datetime Creation
The datetime
module provides the datetime
class for working with both dates and times.
You can create a datetime
object using the datetime()
constructor, specifying the year, month, day, hour, minute, second, and microsecond.
my_datetime = datetime.datetime(2021, 12, 25, 20, 0, 0)
You can also create datetime objects for the current date and time using the now()
method:
current_datetime = datetime.datetime.now()
You can format datetime objects into strings using the strftime()
method, which allows you to specify a format string with various placeholders.
formatted_datetime = current_datetime.strftime("%Y-%m-%d %H:%M:%S")
print(formatted_datetime)
Datetime Arithmetic
You can perform arithmetic operations on datetime objects, such as calculating time differences and adding or subtracting time intervals.
The result will be a timedelta object representing the difference or the modified datetime.
time_difference = current_datetime - my_datetime
print(time_difference)
new_datetime = current_datetime + datetime.timedelta(days=7)