Get Current Date and Time

PUBLISHED ON APRIL 9, 2020

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.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 python application. You can format date and time in different ways using built-in date time format specifiers or directives in Python.

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

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)

Results:

$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 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"))

Result

$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

Reference : https://www.pythonpip.com/python-tutorials/get-current-date-and-time-with-examples/

Last updated