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>
Written by Roman Koblov
Related protips
1 Response
good job!
over 1 year ago
·
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Python
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#