To get the current datetime in Python, you can use the datetime module and datetime.now() function which returns the date and time.
import datetime
currentDateTime = datetime.datetime.now()
print(currentDateTime)
#Output:
2022-08-19 08:33:11.283729
If you want to get the current date, then you can convert the datetime to a date with date().
import datetime
currentDateTime = datetime.datetime.now()
currentDate = currentDateTime.date()
print(currentDate)
#Output:
2022-08-19
When working in Python, many times we need to create variables which represent dates and times. When creating and displaying values related to date and times, sometimes we need to display the current date and time.
To get the current datetime in Python, you can use the datetime module.
The datetime module has many great functions which allow you to work with dates and times in Python.
To get the current datetime in Python, you can use the datetime module and datetime.now() function which returns the date and time.
Below shows you how to get the current datetime in Python.
import datetime
currentDateTime = datetime.datetime.now()
print(currentDateTime)
#Output:
2022-08-19 08:33:11.283729
How to Get Current Date in Python
If you only want to get the current date and don’t care about the time, you can use the datetime date() function.
The datetime date() function removes the time from a datetime variable and returns just the date.
Below shows you how to get the current date in Python.
import datetime
currentDateTime = datetime.datetime.now()
currentDate = currentDateTime.date()
print(currentDate)
#Output:
2022-08-19
Hopefully this article has been useful for you to learn how to get the current datetime in Python.