
PYTHON — Date and Time Methods in Python
The great myth of our times is that technology is communication. — Libby Larsen
Date and Time Methods in Python
In Python, the datetime module provides various attributes and methods that can be used with datetime objects. These attributes and methods allow you to retrieve specific information about the date and time.
To demonstrate, let’s start by obtaining the current month and year using the datetime module:
import datetime
# Get the current date and time
now = datetime.datetime.now()
# Retrieve the current month
current_month = now.month
print(current_month) # Output: 10 (for October)
# Retrieve the current year
current_year = now.year
print(current_year) # Output: 2023In this example, the month attribute is used to obtain the current month, and the year attribute is used to retrieve the current year from the datetime object.
You can explore all available attributes and methods of the datetime module by using the dir() function with a datetime object as a parameter:
print(dir(now))The above code will display a list of all the attributes and methods associated with the datetime object.
Additionally, the datetime module provides other useful attributes and methods, such as second to retrieve the current second, and weekday() to obtain the day of the week as an integer (where Monday is 0 and Sunday is 6).
# Retrieve the current second
current_second = now.second
print(current_second)
# Retrieve the day of the week
current_weekday = now.weekday()
print(current_weekday)You can experiment with these attributes and methods in a Python REPL environment or refer to the official datetime documentation for further details.
By leveraging the attributes and methods of the datetime module, you can manipulate and extract valuable information from date and time objects in Python.






