You can get today's date and time in Python using the datetime
module.
Using the datetime
Module
The datetime
module provides classes for manipulating dates and times. The datetime.datetime.now()
function is the easiest way to get the current date and time.
import datetime
now = datetime.datetime.now()
print(now)
This code will print the current date and time in the format YYYY-MM-DD HH:MM:SS.microseconds
.
Getting Only the Date
If you only need the date, you can use the datetime.date.today()
function.
import datetime
today = datetime.date.today()
print(today)
This will print the current date in the format YYYY-MM-DD
.
Formatting the Output
You can format the output using the strftime()
method. This method allows you to specify a format string that determines how the date and time are displayed.
import datetime
now = datetime.datetime.now()
formatted_date = now.strftime("%Y-%m-%d %H:%M:%S")
print(formatted_date)
This will print the date and time in the format YYYY-MM-DD HH:MM:SS
. You can customize the format string to suit your specific needs. Refer to the Python documentation for a complete list of format codes. For example, %A
represents the full weekday name and %B
represents the full month name.
Summary
In summary, the easiest way to get the current date and time is by using datetime.datetime.now()
. If you only need the current date, use datetime.date.today()
. Use strftime()
to format the output.