简体   繁体   中英

Python: Convert Varbinary type timestamp to unix time stamp

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.

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.

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

If you get string it will be as following:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM