Hassan Baig Hassan Baig - 1 year ago 101
Python Question

Converting DateTimeField in Django to Unix time

In a Django project of mine, I'm using

in a model. This essentially has python

What's the fastest way convert this to time since epoch (in seconds)?

Answer Source

In Python 3.3+ you can use datetime.timestamp():

>>> datetime.datetime(2012,4,1,0,0).timestamp()

For earlier version of Python, you can do:

# Format it into seconds
>>> datetime.datetime(2012,04,01,0,0).strftime('%s')

# OR, subtract the time with 1 Jan, 1970 i.e start of epoch time
# get the difference of seconds using `total_seconds()`
>>> (datetime.datetime(2012,04,01,0,0) - datetime.datetime(1970,1,1)).total_seconds()
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download