Python datetime Install & Usage Guide
To install the datetime library, you can run the pip command in the command line.
pip install datetime
After installation is complete, you can import the datetime library in Python scripts using the import statement.
import datetime
Next, you can use various functions and classes in the datetime library to manipulate dates and times. Here are some common examples of how to use the datetime library:
- Obtain the current date and time:
current_datetime = datetime.datetime.now()
print(current_datetime)
- Get the specified date and time.
specified_datetime = datetime.datetime(2022, 1, 1, 12, 0, 0)
print(specified_datetime)
- Retrieve the different parts of the date and time.
year = current_datetime.year
month = current_datetime.month
day = current_datetime.day
hour = current_datetime.hour
minute = current_datetime.minute
second = current_datetime.second
print(year, month, day, hour, minute, second)
- Format the date and time:
formatted_datetime = current_datetime.strftime("%Y-%m-%d %H:%M:%S")
print(formatted_datetime)
- Parse the string into a date and time.
parsed_datetime = datetime.datetime.strptime("2022-01-01 12:00:00", "%Y-%m-%d %H:%M:%S")
print(parsed_datetime)
This is just a small part of the functionality of the datetime library, there are many other functions and classes available for handling dates and times. You can refer to the Python official documentation or other tutorials to further understand how to use the datetime library.