# Python datetime and Plotly¶

## do's and don'ts¶

First, import a few modules from the Plotly python package:

In [1]:
import plotly.plotly as py
import plotly.tools as tls
from plotly.graph_objs import *


### The wrong way¶

In [2]:
trace1 = Scatter(
x = ['07/11-07:59:40', '07/11-07:59:42', '07/11-07:59:50', '07/11-08:00:00'],
y = ['10','20','5','15']
)

trace2 = Scatter(
x = ['07/11-07:59:40', '07/11-07:59:43', '07/11-07:59:51', '07/11-08:00:00'],
y = ['1','10','5','10']
)

data = Data([trace1, trace2])

fig = Figure(data= data)

In [3]:
py.iplot(fig, filename='netflix_datetimes1')


Here, the x-coordinates are taken as strings.

As with all string coordinates send to Plotly, each unique x element correspond to a coordinate point. The inferred coordinates are created in sequence, from the first element to last element and from the first trace to the last.

In other words, Plotly cannot infer that '07/11-07:59:43' is in fact smaller than '07/11-07:59:50'.

### The right way¶

Plotly understands Python datetimes (built with the datetime package of the Standard Library). More info on Python datetime can be found here.

So,

In [5]:
from datetime import datetime

def convert_to_datetime(times):
return [datetime.strptime(time+' 2014', '%m/%d-%X %Y') for time in times]

# Note that we must the year to each datetime in order to fully define them

trace1 = Scatter(
x = convert_to_datetime(['07/11-07:59:40',
'07/11-07:59:42',
'07/11-07:59:50',
'07/11-08:00:00']),
y = ['10','20','5','15']
)

trace2 = Scatter(
x = convert_to_datetime(['07/11-07:59:40',
'07/11-07:59:43',
'07/11-07:59:51',
'07/11-08:00:00']),
y = ['1','10','5','10']
)

data = Data([trace1, trace2])

fig = Figure(data= data)

In [6]:
py.iplot(fig, filename='netflix_datetimes2')


### The right way (2)¶

Plotly also understands a specific string format.

If you have the chance to modify the string format, this solution does not require the datetime package:

In [7]:
trace1 = Scatter(
x = ['2014-07-11 07:59:40',
'2014-07-11 07:59:42',
'2014-07-11 07:59:50',
'2014-07/11 08:00:00'],
y = ['10','20','5','15']
)

trace2 = Scatter(
x = ['2014-07-11 07:59:40',
'2014-07-11 07:59:43',
'2014-07-11 07:59:51',
'2014-07-11 08:00:00'],
y = ['1','10','5','10']
)

data = Data([trace1, trace2])

fig = Figure(data= data)

In [8]:
py.iplot(fig, filename='netflix_datetimes3')


Refer to

#### Notebook styling ideas

Big thanks to

In [1]:
from IPython.display import display, HTML
import urllib2
url = 'https://raw.githubusercontent.com/plotly/python-user-guide/master/custom.css'