views:

10864

answers:

4

Can anybody tell what is the module/method used to get current time ???

+22  A: 
>>> from datetime import datetime
>>> datetime.now()
datetime(2009, 1, 6, 15, 8, 24, 78915)

And just the time:

>>> datetime.time(datetime.now())
datetime.time(15, 8, 24, 78915)
Harley
how to extract only the time?
Added to the answer
Harley
how could i compare it as in:a = datetime.time(datetime.now())if a < 2: print 'done'
Just compare it. If you want to know if three seconds elapsed, save the start_time at the beginning of your program and just "datetime.now() - start_time > 3".
bortzmeyer
-1 for not including the link: http://docs.python.org/library/datetime.html
S.Lott
upvote for tolerating newbies! like me!
ehfeng
+5  A: 

>>> from time import gmtime, strftime
>>> strftime("%Y-%m-%d %H:%M:%S", gmtime())
'2009-01-05 22:14:39'

Sean James
+2  A: 
>>> from time import gmtime, strftime
>>> strftime("%a, %d %b %Y %H:%M:%S +0000", gmtime())

Output: 'Tue, 06 Jan 2009 04:54:56 +0000'

That outputs the current GMT in the specified format. There is also a localtime() method.

This page has more details.

Vijay Dev
I must not fully understand this as doing "print strftime("%a, %d %b %Y %H:%M:%S +0000", gmtime())" will lead to the same number being printed twice, irregardless to the actual time. What is going on?
James McMahon
+4  A: 

Do

from time import time

t = time()

t - float number, good for time interval measurement

there is some difference for Unix and Windows platforms.

maxp
use time.clock() on Windows and time.time() on *nix
Corey Goldberg