We could use two modules to get the current time in Python, that are
datetime module to get the current time in Python
>>> from datetime import datetime >>> datetime.now() 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.
>>> datetime.now().strftime('%Y-%m-%d %H:%M:%S') '2018-07-17 22:54:25'
Below is the snippet of directives in the
strftime format string.
||Day of the month as a decimal number [01,31].|
||Hour (24-hour clock) as a decimal number [00,23].|
||Month as a decimal number [01,12].|
||Minute as a decimal number [00,59].|
||Second as a decimal number [00,61].|
||Year with century as a decimal number.|
Only Current Time Without Date
>>> from datetime import datetime >>> datetime.now().time() 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())
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.