Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the current time in Python

What is the module/method used to get the current time?

like image 923
user46646 Avatar asked Jan 06 '09 04:01

user46646


People also ask

What is datetime datetime now () in Python?

Python datetime: datetime. now(tz=None) returns the current local date and time. If optional argument tz is None or not specified, this is like today().

What does time time () do in Python?

time() The time() function returns the number of seconds passed since epoch. For Unix system, January 1, 1970, 00:00:00 at UTC is epoch (the point where time begins).


2 Answers

Use:

>>> import datetime >>> datetime.datetime.now() datetime.datetime(2009, 1, 6, 15, 8, 24, 78915)  >>> print(datetime.datetime.now()) 2009-01-06 15:08:24.789150 

And just the time:

>>> datetime.datetime.now().time() datetime.time(15, 8, 24, 78915)  >>> print(datetime.datetime.now().time()) 15:08:24.789150 

See the documentation for more information.

To save typing, you can import the datetime object from the datetime module:

>>> from datetime import datetime 

Then remove the leading datetime. from all of the above.

like image 180
Harley Holcombe Avatar answered Sep 24 '22 06:09

Harley Holcombe


You can use time.strftime():

>>> from time import gmtime, strftime >>> strftime("%Y-%m-%d %H:%M:%S", gmtime()) '2009-01-05 22:14:39' 
like image 30
Sean James Avatar answered Sep 20 '22 06:09

Sean James