[Tutor] problem in conversion

Magnus Lycka magnus@thinkware.se
Thu, 17 Oct 2002 22:14:54 +0200


At 17:58 2002-10-17 +0000, Carlos Sousa wrote:
>I to all
>
>I need to extract the hour and minute from a field x (x is a timestamp=20
>field in postgres)
>
>printing the content of x['date_part']  is  '2002-02-05 09:30:00.00'
>
>I can extract the hour or the minute but not both.
>
>I=B4m trying to transform it into a string and then see if can find a way=
 to=20
>see if, for instance '09:30' belongs to the string
>
>I hope my problem was understod and If someone could help me it would be=20
>appreciated

Maybe...

There are a number of Python PostgreSQL drivers, and I fear
that they might handle dates differently.

In case the use mxDateTime (which I think they do), you should
have a look at the docs for that. See:
http://www.egenix.com/files/python/mxDateTime.html

If this is the kind of object you have, you could do something
similar to:
 >>> from mx.DateTime import *
 >>> t =3D now()
 >>> print t
2002-10-17 22:02:41.74
 >>> t.hour
22
 >>> t.minute
2
 >>> "%02d:%02d" % (t.hour, t.minute)
'22:02'

Or simply:

 >>> t.time[:5]
'22:02'

Or even better:

 >>> t.strftime('%H:%M')
'22:02'

If you have a string like the one you showed above, you
should be able to do this:

 >>> '2002-02-05 09:30:00.00'[11:16]
'09:30'

Although, I imagine that locale settings might
influence the look of this string... :(

On the other hand, why convert it to a string? You
could as well test like this:

if (t.hour, t.minute) =3D=3D (9,30):
     #do something

This is probably faster, more robust and
easier to understand than the other versions.



--=20
Magnus Lyck=E5, Thinkware AB
=C4lvans v=E4g 99, SE-907 50 UME=C5
tel: 070-582 80 65, fax: 070-612 80 65
http://www.thinkware.se/  mailto:magnus@thinkware.se