How to Encode the Cyclic Properties of Time with Python

When dealing with timestamp data in the context of machine learning, it’s important to encode the properties of time so that your model can utilize the information properly.

In many cases, the cyclic properties of time can be relevant to the problem you’re trying to solve. For example, if you’re building a model to predict road traffic, the time of day is an important factor.

One approach might be to encode the time of day as a number between zero and one, where midnight is zero and 11:59PM is 1. Unfortunately, that distorts the proximity of 11:59pm and midnight.

A better way is to represent time of day as a point on the unit circle, using sine and cosine.

The Python code below is an example of how to do this with datetime objects.