Last Updated: February 25, 2016
·
1.727K
· penpen

Timestamps in Python

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 built-in function for that.
Here are some functions for that from my utils.py

Convert datetime.datetime object to unix timestamp:</p>

def timestamp(datetimeobj): """ Convert datetime object to timestamp """ if type(datetimeobj) is datetime.datetime: return int(time.mktime(datetimeobj.timetuple())) else: return int(datetimeobj) </code>
</pre>
Convert unix timestamp to datetime.datetime object:</p>
def fromtimestamp(timestamp): """ Convert timestamp to datetime object""" return datetime.datetime.fromtimestamp(timestamp) </code>
</pre>
Return current unix timestamp:</p>
def timestampnow(): """ Return current unix timestamp """ return timestamp(datetime.datetime.now())</code></pre>
Enjoy!</p>

1 Response
Add your response

good job!

over 1 year ago ·