0

I have a mysql database that store timestamp in a varbinary column and my goal is to convert this to unix time stamp so I can do a elapse time between two time slots.

+---------+------------+-------------------+----------------+--------------------------+
| some_id | some_name  | user_registration | some_count     | some_value_yes_no        |
+---------+------------+-------------------+----------------+--------------------------+
|  some_id | some_user | 20091129060140    |           2685 |                        1 |
+---------+------------+-------------------+----------------+--------------------------+

Here the user_registration is the mysql varbinary(14), assume after connecting and extracting this data, I have the user_registration stored in a variable from python side,

...
    timestamp = row['user_registration']

how can I convert this to a unix time stamp to so I can do a time difference between a another time stamp like this. I looked at the http://docs.python.org/2/library/datetime.html but I couldn't find any example like this.

3 Answers 3

3

You can first convert it into a datetime object and then into a Unix time using time module.

import datetime
import time

user_reg_time = datetime.datetime.strptime("20091129060140", "%Y%M%d%H%m%S")
epochs_time = time.mktime(user_time_reg.timetuple())

BTW if you just need to compare time, you don't really need to convert to Unix time; Python has a built-in "timedelta" object. This will work too:

import datetime
import time

user_reg_time = datetime.datetime.strptime("20091129060140", "%Y%M%d%H%m%S")
if datetime.datetime.now() - user_reg_time > datetime.timedelta(weeks=4):
    print "User was registered more than 4 weeks ago"

You can get more info about timedelta at Python official docs.

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

2 Comments

I need to do a time difference between two time slots where both time slots are like I have mentioned, and want the difference in days
Convert the other time into datetime as well using strptime. Then subtract them and compare using datetime.timedelta(days=...)
1
>>> import time
>>> 
>>> date_str = "20091129060140"
>>> time_tuple = time.strptime(date_str, "%Y%m%d%H%M%S")
>>> timestamp = time.mktime(time_tuple)
>>> 
>>> print timestamp
1259470900.0

Comments

0

If you get string it will be as following:

from datetime import datetime
datetime.strptime(timestamp, '%Y%m%d%H%M%S');

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.