Skip to main content
python-current-date

Get Current Date and Time with Examples

This python tutorial help to get the current date using python 3. The Python datetime class can be used to get and manipulate date and time.

We will also format the date and time in different formats using strftime() method.

This libs provides a lot of methods and properties to express the date and time in programs in a variety of formats.

The today() method of DateTime class can be used to get the current date and time in the python application.

You can format date and time in different ways using built-in date-time format specifiers or directives in Python.

How To Get today Date

You can find the current date in a variety of ways. To complete this task, we will make use of the date class in the datetime module.

from datetime import date

today = date.today()
print("Today's date:", today)

in the above code, We have imported the date class from the datetime module. Then, we used the date.today() method to get the current local date.

Current Date and Time in Python Using datetime.today() Method

You can also get the current date and time, you can use datetime class of the datetime module.

import datetime

# getting current date and time
d = datetime.datetime.today()
print('Current date and time: ', d)

# getting current year
print('Current year: ', d.year)

#getting current month
print('Current month: ', d.month)

#getting current day
print('Current day: ', d.day)

# getting current hour
print('Current hour: ', d.hour)

# getting current minutes
print('Current minutes: ', d.minute)

# getting current Seconds
print('Current seconds: ', d.second)

# getting current microsecond
print('Current micro seconds: ', d.microsecond)

Output:

$python main.py
('Current date and time: ', datetime.datetime(2020, 3, 17, 12, 45, 52, 364660))
('Current year: ', 2020)
('Current month: ', 3)
('Current day: ', 17)
('Current hour: ', 12)
('Current minutes: ', 45)
('Current seconds: ', 52)
('Current micro seconds: ', 364660)

Format Current Date in Python Using strftime Function

The strftime method is used to format a date in Python. You can convert a date into any possible desired format by using this method.

You can pass date format specifiers or directives to format the date into the desired format.

import datetime

d = datetime.datetime.today()

print ('Current date and time:', d)

# Converting date into DD-MM-YYYY format
print(d.strftime('%d-%m-%Y'))

#with directive
print(d.strftime("%d-%B-%Y %H:%M:%S"))

Output:

$python main.py
('Current date and time:', datetime.datetime(2020, 3, 17, 12, 50, 14, 661425))
17-03-2020
17-March-2020 12:50:14

Leave a Reply

Your email address will not be published. Required fields are marked *