How to convert datetime to timestamp in Python

Get current timestamp

import time

Convert datetime to timestamp

import time
from datetime import datetime
d = datetime(2017, 6, 11, 0, 0)

unixtime = time.mktime(d.timetuple())

In Python 3.3+ you can use timestamp() instead:

datetime.datetime(2017, 6, 11, 0, 0).timestamp()

Convert timestamp to datetime

import pytz
from datetime import datetime

utc_dt = datetime.utcfromtimestamp(unixtime).replace(tzinfo=pytz.utc) 

# using calendar
import calendar
from datetime import datetime

dt = datetime.utcnow()
comments powered by Disqus