syntax.us Let the syntax do the talking
Blog Contact Posts Questions Tags Hire Me

Question:
In Python how do I convert a datetime to unix-time?

I often encounter Python use-cases asking me to convert datetime to different formats.

One format I see often is 'epoch-time' or sometimes called 'unix-time'.

It is an integer format (usually but sometimes float) which represents a datetime as the number of seconds since 1970-01-01 00:00:00.

The datetime 1970-01-01 00:00:00 is sometimes called the 'epoch'.

So, a unix-time of 59 would be 59 seconds after the epoch and thus represent this datetime: 1970-01-01 00:00:59

Here is a more interesting demonstration of converting a date to unix-time:
from datetime import datetime
ds1 = '2014-10-31'
dd1 = datetime.strptime(ds1, '%Y-%m-%d')
print(dd1)
unix_time = (dd1-datetime(1970,1,1)).total_seconds()
print(unix_time)
I have found that unix-time is a useful format for helping me to serve plots of time-series data to the web using a combo of Rails and D3.js
syntax.us Let the syntax do the talking
Blog Contact Posts Questions Tags Hire Me