How to work with a datetime.datetime object returned from an Oracle query in Python
I have a query against an Oracle database using cx_Oracle. The results from the query come as
(datetime.datetime(2010, 11, 25, 14, 30, 47),)
I get this by using the below code:
#!/usr/bin/python
import obi
from datetime import datetime
conn = obi.connect_obi()
query = obi.run_query(conn, "SELECT co开发者_JAVA技巧lumn FROM table_name")
for i in query:
print i
What I want to do is extract the time, date, etc. from the results.
I've tried using various datetime methods, but I can't figure how to access the individual elements from the returned list. I get various errors about it being a tuple, a list ,etc depending on what attempts I make. I've looked at examples on Google and I can get those to work fine - what do I need to do differently to successfully access the time/date in this datetype?
Thanks! Jack
x = (datetime.datetime(2010, 11, 25, 14, 30, 47),)
is a tuple.
dt = x[0]
is the first element, which is your datetime.
dt.year
is the year of the datetime. etc.
The returned value, (datetime.datetime(2010, 11, 25, 14, 30, 47),)
is really a tuple. Note that it is enclosed in parenthesis and (most importantly) it has a comma just after the date. Just like a comma between two expressions turn them in a pair tuple (such as 1, 2
) a comma after some expression turns the value in a tuple with just one element. More about it in the this section of the Python tutorial (more specifically here).
An example:
>>> (datetime.datetime(2010, 11, 25, 14, 30, 47),)
(datetime.datetime(2010, 11, 25, 14, 30, 47),)
>>> t = (datetime.datetime(2010, 11, 25, 14, 30, 47),)
To get the date, just get the first element of the tuple
>>> date = t[0]
>>> date
datetime.datetime(2010, 11, 25, 14, 30, 47)
>>> date.year
2010
>>> date.month
11
精彩评论