2

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 column 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

2 Answers 2

2
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.

Sign up to request clarification or add additional context in comments.

1 Comment

Happy to help. Click the checkbox outline next to this answer to "accept" it and close the question. Welcome to SO!
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.