To print datetimes in Python, you can use the strftime() method, which allows you to format a datetime object as a string.
Here's an example code that prints the current date and time in a specific format:
from datetime import datetimenow = datetime.now()# Format the datetime object as a stringdate_time = now.strftime("%Y-%m-%d %H:%M:%S")print("Current date and time:", date_time) |
In this code, we first import the datetime module and create a datetime object representing the current date and time using the now() method. Then, we use the strftime() method to format the datetime object as a string with the format "%Y-%m-%d %H:%M:%S", which corresponds to the year, month, day, hour, minute, and second in a specific order. Finally, we print the formatted string using the print() function.
You can customize the format string to display the datetime in any desired format. The available format codes are documented in the Python documentation.