## How to convert STRING to DateTime in Python
def Kickstarter_Example_53():
print()
print(format('How to convert STRING to DateTime in Python','*^82'))
import warnings
warnings.filterwarnings("ignore")
# Load Libraries
from datetime import datetime
from dateutil.parser import parse
import pandas as pd
# Create a string variable with a datetime
date_start = '2012-03-03'
# Convert the string to datetime format
print()
print(datetime.strptime(date_start, '%Y-%m-%d'))
# Create a list of strings as dates
dates = ['7/2/2017', '8/6/2016', '11/13/2015', '5/26/2014', '5/2/2013']
# Use parse() to attempt to auto-convert common string formats
print()
print(parse(date_start))
print()
print([parse(x) for x in dates])
# Use parse, but designate that the day is first
print()
print(parse(date_start, dayfirst=True))
# Create a dataframe
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.dtypes)
# Convert df['date'] from string to datetime
print()
print(pd.to_datetime(df['date']))
print(pd.to_datetime(df['date']).dtypes)
Kickstarter_Example_53()