Reputation: 21
I have a string of series in this format: 2017-12-04T08:30:00+11:00
. I am trying to convert this into a datetime object.Highlighted with yellow colour.See Image:
How to fetch date from the start, end & updated columns and convert these object to date?
I have tried:
def ISOtstr(iso):
dcomponents = [1,1,1]
dcomponents[0] = iso[:4]
dcomponents[1] = iso[5:7]
dcomponents[2] = iso[8:10]
tcomponents = [1,1,1]
tcomponents[0] = iso[11:13]
tcomponents[1] = iso[14:16]
tcomponents[2] = iso[17:19]
d = dcomponents
t = tcomponents
string = "{}-{}-{} {}:{}:{}".format(d[0],d[1],d[2],t[0],t[1],t[2])
return string
import datetime
string = a.iloc[1]['start']
date_string = ISOtstr(string)
date_obj = datetime.datetime.strptime(date_string, '%Y-%m-%d %H:%M:%S')
print(date_obj)
print(type(date_obj))
for item in df['start'].iteritems():
datetime.datetime.strptime(df['start'], "%a-%b-%d-%H-%M-%S-%Z-%Y")
import datetime
date_time_str = a['start']
date_time_obj = datetime.datetime.strptime(date_time_str, '%Y-%m-%d %H:%M:%S.%f')
print('Date:', date_time_obj.date())
print('Time:', date_time_obj.time())
print('Date-time:', date_time_obj)
TypeError: strptime() argument 1 must be str, not Series
IPython Notebook: https://drive.google.com/file/d/1YbQZOCxtLLUiB4YyivRhM5W6n6CVVh3y/view?usp=sharing
Upvotes: 2
Views: 510
Reputation: 7241
There is a dateutil module in Python that does all magical date parsing job:
>>> import dateutil.parser
>>> dateutil.parser.parse('2017-12-04T08:30:00+11:00')
datetime.datetime(2017, 12, 4, 8, 30, tzinfo=tzoffset(None, 39600))
Upvotes: 0
Reputation: 51
You need to pass datetime.datetime.strptime() a string, not series. df['start'] is indexing your 'start' column. If you want to stick with specifically the datetime module, you could look into using df.apply, or iterate over your data.
However, others mentioned before I could, pandas has a built-in datetime method that will do exactly as you wish!
To start you off (sorry haven't much time right now!), you'd essentially pass a series of your df as an argument to the pandas class like so
df['start']=pd.to_datetime(df['start'],format='%foo%bar)
The returned object will be a series you can assign to your 'start' series.
Upvotes: 1
Reputation: 4864
pandas has a very useful pd.to_datetime
function, which does what you want.
Upvotes: 1