Reputation: 830
I have following string value obtained from a pandas dataframe.
u'1:19 AM Eastern, Tuesday, May 16, 2017'
How do I convert it to a datetime.datetime(2017,5,16) object?
Thx.
Upvotes: 0
Views: 81
Reputation: 14689
You need to create a custom date parser, to give you some ideas here's a reproducible example:
import pandas as pd
import datetime
from StringIO import StringIO
st = u'01:19 AM Eastern, Tuesday, May 16, 2017'
def parse_date(date_string):
date_string = ",".join(date_string.split(',')[-2:]).strip()
return datetime.datetime.strptime(date_string, '%B %d, %Y')
df = pd.read_csv(StringIO(st), header=None, sep="|", date_parser=parse_date, parse_dates=[0])
If you print the dataFrame content as follows, :
print("dataframe content")
print(df)
you will get this output:
dataframe content
0
0 2017-05-16
checking the dtypes confirms that the column is now of type datetime:
print("dataframe types")
print(df.dtypes)
output:
dataframe types
0 datetime64[ns]
dtype: object
Upvotes: 2