[Tutor] how to extract time from datetime.date.time()

Terry Carroll carroll at tjc.com
Thu Nov 16 20:06:12 CET 2006


On Thu, 16 Nov 2006, Asrarahmed Kadri wrote:

> I want to extract hh:mm:ss from below mentioned code:
> 
> import datetime
> >>> t = datetime.datetime.now()
> >>> print t
> 2006-11-16 16:59:02.843000
> 
> How to do it?

In addition to the suggestions you've seen, now() returns a datetime 
object, and a datetime object has a time() method that returns a time 
object:

>>> dt = datetime.datetime.now()
>>> t = dt.time()
>>> print t
10:55:06.801000

You can get this into a string easily, if you want:

>>> s = str(t)
>>> s
'10:55:06.801000'

or, if you want the ugly one-liner:

>>> s = str(datetime.datetime.now().time())
>>> s
'10:56:04.361000'

If you don't want the fractional part of the seconds, you can use the 
ordinary string methods to find the dot and slice off only the part you 
want to keep.  For example:

>>> s[0:s.find('.')]
'10:56:04'

Digression: It is possible to combine this with the prior ugly one-liner
to produce the result you want, but it would require invoking now() twice,
with the result that one instance would be used to generate the string in
which you search for the '.', and the other used as the string from which
the hh:mm:ss is sliced, where the two instances will have different
values, but identical formats, which is good enough here, but that strikes
me as just inelegant, and requires a pointless second invocation of now(),
and besides, the end result will be nearly as unreadable as this sentence.

But, just for the hell of it:

>>> s = str(datetime.datetime.now().time())[0:str(datetime.datetime.now().time()).find('.')]
>>> s
'11:01:32'



More information about the Tutor mailing list