Title: Convert A Variable To A Time Variable In Pandas
Slug: pandas_convert_to_datetime
Summary: Convert A Variable To A Time Variable In Pandas
Date: 2016-05-01 12:00
Category: Python
Tags: Data Wrangling
Authors: Chris Albon


In [1]:
# Import Preliminaries
import pandas as pd

In [2]:
# Create a dataset with the index being a set of names
raw_data = {'date': ['2014-06-01T01:21:38.004053', '2014-06-02T01:21:38.004053', '2014-06-03T01:21:38.004053'],
        'score': [25, 94, 57]}
df = pd.DataFrame(raw_data, columns = ['date', 'score'])
df


Out[2]:
date score
0 2014-06-01T01:21:38.004053 25
1 2014-06-02T01:21:38.004053 94
2 2014-06-03T01:21:38.004053 57

In [3]:
# Transpose the dataset, so that the index (in this case the names) are columns
df["date"] = pd.to_datetime(df["date"])

In [4]:
df = df.set_index(df["date"])

In [5]:
df


Out[5]:
date score
date
2014-06-01 01:21:38.004053 2014-06-01 01:21:38.004053 25
2014-06-02 01:21:38.004053 2014-06-02 01:21:38.004053 94
2014-06-03 01:21:38.004053 2014-06-03 01:21:38.004053 57