How to get Current Date in Python 3

In This Python tutorial we are going to learn how to get current date in python 3 programming. We will also learn how to get current year, month and day separately.

Get Current Date with Current Time in Python 3

To get the current date in python 3 we can use datetime module. So first we have to import datetime module in our python script.

#!/usr/bin/python3
import datetime

Then we can get the current date from datetime module using the date.today() method.

#!/usr/bin/python3
import datetime

current_date = datetime.date.today()
print(current_date)

Above Python 3 script will output the today’s date in "year-month-date" format

2016-09-02

From the current date we can also extract the current year, month and day separately.

#!/usr/bin/python3
import datetime

current_date = datetime.date.today()
current_year = current_date.year # Extract current year only
current_month = current_date.month # Extract current month only
current_day = current_date.day # Extract current day only

Format Date with strftime function in Python 3

Python datetime module by default output the current date in "year-month-date" format, But if we want we can use strftime() method to output the date in different formats.

Example 1

#!/usr/bin/python3
import datetime

current_date = datetime.date.today()
current_date = current_date.strftime("%d-%m-%Y")
print(current_date)

In the above example, we change the format of the current_date to the "date-month-year" format using strftime() function.

02-09-2016

Example 2

#!/usr/bin/python3
import datetime

current_date = datetime.date.today()
current_date = current_date.strftime("%d-%B-%Y")
print(current_date)

In the above example, we display the Month as fullname(%B) instead of decimal number.

02-September-2016

You can get the full list of string format use in python strftime function from the http://strftime.org/.

Get Current Date with Current Time

To get both current date and time we can use datetime.datetime.now() method.

#!/usr/bin/py
import datetime

date_time = datetime.datetime.now()
print(date_time.strftime("%Y-%b-%d %H:%M"))

As per the above example, first we assign today date and time to the date_time variable. Then we displayed the date and time in "year-month-date hour:minutes" using strftime function. The output will be something similar to.

2016-Sep-02 12:19

 

You can refer to the datetime documentation For more advanced python 3 datetime functions.