from datetime import date
current_date = date.today()
print(current_date)
Output
2022-07-03
Get the current date using datetime module in Python. The above code does the same.
Below are some code example that can be used to get today's date in different date formats.
Code Example - Current date in format(dd/mm/yyyy)
from datetime import date
current_date = date.today()
result = current_date.strftime("%d/%m/%Y")
print(result)
Output
26/05/2022
Code Example - Current date in Format(month_name-dd-yyyy)
from datetime import date
current_date = date.today()
result = current_date.strftime("%b-%d-%Y")
print(result)
Output
May-26-2022
Code Example - Current date in Format(month_name dd, yyyy)
from datetime import date
current_date = date.today()
result = current_date.strftime("%B %d, %Y")
print(result)
Output
May 26, 2022
Code Example - Current date in Format(mm/dd/yy)
from datetime import date
current_date = date.today()
result = current_date.strftime("%m/%d/%y")
print(result)
Output
05/26/22
In the above code examples, we have learned to get today's date using python module datetime. But if you want to get time along with the current date, you can use the below code examples.
We will use datetime class from datetime module to do that.
from datetime import datetime
result = datetime.now()
print(result)
Output
2022-05-26 08:43:04.554097
Explanation:
Python's 'datetime' module provides a date class that is used to store and manipulate dates. The 'date' class has a today() function that returns the current date as a 'date' object. The date object has 'month' and 'year' attributes that can be used to get the current month and year separately.
Code Example
from datetime import date
# full date
current_date = date.today()
# get current day
current_day = current_date.day
print(current_day)
# get current month
current_month = current_date.month
print(current_month)
# get current year
current_year = current_date.year
print(current_year)
Output
26
5
2022
Explanation:
The article is discussing how to get the current date in Python in multiple formats. The conclusion is that you can use the datetime module to get the current date in Python in multiple formats. We have explained multiple methods in order to do that. If you found something useful about the same, please mention in the comment section.
0 Comments