0

I have a query that returns a date time in sql, example:

+---------------------+
| created             |
+---------------------+
| 2008-07-31 21:42:52 |
+---------------------+

In my python code I am doing the following to capture the data by calling the query. Here is my python code:

query_item_created_f = None
                    query_item_created_f = query_item_created.format(parent_id=question_id)
                    self.dbCursor.execute(query_item_created_f)
                    created_date = self.dbCursor.fetchall()
                    print created_date

I get the data and time in following format:

({'created': datetime.datetime(2008, 7, 31, 21, 42, 52)},)

How can I change this to unix data time?

2 Answers 2

2

Call the .timetuple() method on the datetime.datetime object, pass that to time.mktime() to create a UNIX timestamp:

>>> import datetime
>>> dt = datetime.datetime(2008, 7, 31, 21, 42, 52)
>>> import time
>>> time.mktime(dt.timetuple())
1217533372.0
Sign up to request clarification or add additional context in comments.

4 Comments

dt = datetime.datetime(int(created_date)) TypeError: int() argument must be a string or a number, not 'tuple I am getting this error, I cast it to int just like this: print created_date dt = datetime.datetime(int(created_date)) unix_time = time.mktime(dt.timetuple()
problem is my date is in following format 2008-07-31 21:42:52 and according to your example I need to separate them to integers.
No, you showed that your database returns a datetime.datetime() object already; in my example I recreate the same object so that I can call the .timetuple() method on it. You do not need to do the same.
In other words, use print time.mktime(created_time[0]['created'].timetuple())
0

Try with strftime:

'datetime.datetime(2008, 7, 31, 21, 42, 52).strftime('%Y-%m-%d %H:%M:%S')

2 Comments

That's not a UNIX time value (seconds since the epoch).
seconds since the epoch the catch :)

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.