Reputation: 18810
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.
Upvotes: 0
Views: 1012
Reputation: 6627
If you get string it will be as following:
from datetime import datetime
datetime.strptime(timestamp, '%Y%m%d%H%M%S');
Upvotes: 0
Reputation: 6005
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.
Upvotes: 3
Reputation: 2401
>>> 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
Upvotes: 1