A question about time
John Machin
sjmachin at lexicon.net
Thu Jun 9 18:24:40 EDT 2005
Jan Danielsson wrote:
> Hello all,
>
> I have a list of servers which an application connects to. If the
> connection fails, the application should mark the server as temporarily
> unavailable, and should try to use the server again after x units of time.
>
> In C, I would do this:
>
> server.invalidUntil = time(NULL) + 5*60; // five minute delay
>
> ..and the check:
>
> if(time(NULL) > server.invalidUtil)
> {
> // use server
> }
>
> So the whole thing very simple... But how do I do that in Python?
>
> I have found datetime.datetime.now(), but I don't understand what
> "format" it returns the time in. I assume it's an object of some sort..
Everything in Python is an object. Objects can be inspected. The builtin
function repr(obj) gives a diagnostic and often compilable
REPResentation of the object, and str(obj) [think STRing] gives a
"pretty" picture. Sometimes repr() and str() produce the same results.
To understand what "format" it's in, read the documentation; in this
case, it's found at:
http://www.python.org/doc/2.4.1/lib/datetime-datetime.html
and play around with the command-line interpreter (example below) or
your favourite IDE.
>>> import datetime
>>> t1 = datetime.datetime.now(); t2 = t1 + datetime.timedelta(minutes=5)
[somewhat later]
>>> t3 = datetime.datetime.now()
>>> for x in t1, t2, t3: print str(x), repr(x)
...
2005-06-10 07:39:15.312000 datetime.datetime(2005, 6, 10, 7, 39, 15, 312000)
2005-06-10 07:44:15.312000 datetime.datetime(2005, 6, 10, 7, 44, 15, 312000)
2005-06-10 07:56:03.031000 datetime.datetime(2005, 6, 10, 7, 56, 3, 31000)
>>> t3 > t2
True
> But how do I do if I want the current time as an integer (unix
> timestamp) in Python?
The Python time module would be a good starting point.
More information about the Python-list
mailing list