Title: Converting Strings To Datetime
Slug: strings_to_datetime
Summary: Converting Strings To Datetime
Date: 2016-05-01 12:00
Category: Python
Tags: Basics
Authors: Chris Albon
In [1]:
from datetime import datetime
from dateutil.parser import parse
import pandas as pd
In [2]:
war_start = '2011-01-03'
In [3]:
datetime.strptime(war_start, '%Y-%m-%d')
Out[3]:
In [4]:
attack_dates = ['7/2/2011', '8/6/2012', '11/13/2013', '5/26/2011', '5/2/2001']
In [5]:
[datetime.strptime(x, '%m/%d/%Y') for x in attack_dates]
Out[5]:
In [6]:
parse(war_start)
Out[6]:
In [7]:
[parse(x) for x in attack_dates]
Out[7]:
In [8]:
parse(war_start, dayfirst=True)
Out[8]:
In [9]:
data = {'date': ['2014-05-01 18:47:05.069722', '2014-05-01 18:47:05.119994', '2014-05-02 18:47:05.178768', '2014-05-02 18:47:05.230071', '2014-05-02 18:47:05.230071', '2014-05-02 18:47:05.280592', '2014-05-03 18:47:05.332662', '2014-05-03 18:47:05.385109', '2014-05-04 18:47:05.436523', '2014-05-04 18:47:05.486877'],
'value': [1, 1, 1, 1, 1, 1, 1, 1, 1, 1]}
df = pd.DataFrame(data, columns = ['date', 'value'])
print(df)
In [10]:
pd.to_datetime(df['date'])
Out[10]: