Get current date and time in Python
In Python, you can get the current date and time using the built-in datetime
module. Here's an example of how to do it:
import datetime # Get the current date and time now = datetime.datetime.now() # Print the current date and time print("Current date and time:") print(now)
This will output the current date and time in the following format:
Current date and time: 2023-02-27 14:45:00.123456
You can also format the output to display only the parts of the date and time that you're interested in. Here's an example:
import datetime # Get the current date and time now = datetime.datetime.now() # Format the date and time formatted_date = now.strftime("%Y-%m-%d %H:%M:%S") # Print the formatted date and time print("Current date and time:") print(formatted_date)
This will output the current date and time in the following format:
Current date and time: 2023-02-27 14:45:00
You can customize the format string passed to the strftime()
method to get different date and time formats. The %Y
, %m
, %d
, %H
, %M
, and %S
codes represent the year, month, day, hour, minute, and second respectively.