How to Get the Current Time in Python

We could use two modules to get the current time in Python, that aredatetime and time.

datetime module to get the current time in Python

>>> from datetime import datetime
datetime.datetime(2018, 7, 17, 22, 48, 16, 222169)

It returns the datetime object that includes the date time information including year, month, day and time.

If you prefer a string format, then you could use a strftime method to convert the datetime object instance to a string format as defined in the argument.

>>>'%Y-%m-%d %H:%M:%S')
'2018-07-17 22:54:25'

Below is the snippet of directives in the strftime format string.

Directive Meaning
%d Day of the month as a decimal number [01,31].
%H Hour (24-hour clock) as a decimal number [00,23].
%m Month as a decimal number [01,12].
%M Minute as a decimal number [00,59].
%S Second as a decimal number [00,61].
%Y Year with century as a decimal number.

Only Current Time Without Date

>>> from datetime import datetime
datetime.time(23, 4, 0, 13713)

time module to get the current time in Python

import time
time.strftime('%Y-%m-%d %H:%M:%S', time.localtime())
'2018-07-17 21:06:40'

As its name indicates, time.localtime() returns the local time in your time zone. If UTC time is preferred, then time.gmtime() is the right choice.