How to convert datetime to timestamp in Python Python 08.06.2017

Get current timestamp

import time
time.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) 
print(utc_dt.strftime("%d.%m.%Y"))

# using calendar
import calendar
from datetime import datetime

dt = datetime.utcnow()
calendar.timegm(dt.utctimetuple())

# python 3
timestamp = 1545730073
dt_object = datetime.fromtimestamp(timestamp)