Sometimes you need to use unix timestamp in Python for data exchange with external application (e.g. PunBB stores date as timestamp). Unfortunately Python doesn’t have a built-in function for that.
Here are some functions for that from my utils.py.
Convert datetime.datetime object to unix timestamp:
def timestamp(datetime_obj):
""" Convert datetime object to timestamp """
if type(datetime_obj) is datetime.datetime:
return int(time.mktime(datetime_obj.timetuple()))
else:
return int(datetime_obj)
Convert unix timestamp to datetime.datetime object:
def from_timestamp(timestamp):
""" Convert timestamp to datetime object"""
return datetime.datetime.fromtimestamp(timestamp)
Return current unix timestamp:
def timestamp_now():
""" Return current unix timestamp """
return timestamp(datetime.datetime.now())
Enjoy!