Reputation: 1729
I am using a function to bring my date consistent in a column, it goes like this
from dateutil.parser import parse
def dateconv1(x):
c = parse(x)
return c
so if i will use it as, it works fine
In[15]:dateconv1("1 / 22 / 2016 15:03")
Out[15]:datetime.datetime(2016, 1, 22, 15, 3)
But when I pass it in variable like this
a= 1 / 22 / 2016 15:03
In[16]:dateconv1(str(a))
It doesn't work, so how to bring it in quotes or as a string, every help will be appreciating
Upvotes: 0
Views: 151
Reputation: 210832
assuming that you are talking about pandas dataset, you can use pandas to_datetime() method:
In [66]: dates = ['1 / 22 / 2016 15:03', 'Jul 22 2016 12:32PM', 'Jul 22 2016 5:40PM',
....: 'Jul 22 2016 8:31PM', 'Jul 23 2016 2:01PM', 'Jul 23 2016 7:24PM',
....: 'Jul 24 2016 4:30PM', 'Aug 1 2016 4:00PM', 'Aug 1 2016 7:49PM']
In [67]: df = pd.DataFrame({'d':dates})
In [68]: df.dtypes
Out[68]:
d object
dtype: object
d object
- means that the d
column is of a string (object) dtype
In [69]: df
Out[69]:
d
0 1 / 22 / 2016 15:03
1 Jul 22 2016 12:32PM
2 Jul 22 2016 5:40PM
3 Jul 22 2016 8:31PM
4 Jul 23 2016 2:01PM
5 Jul 23 2016 7:24PM
6 Jul 24 2016 4:30PM
7 Aug 1 2016 4:00PM
8 Aug 1 2016 7:49PM
let's convert it to datetime
dtype:
In [70]: df.d = pd.to_datetime(df.d)
In [71]: df
Out[71]:
d
0 2016-01-22 15:03:00
1 2016-07-22 12:32:00
2 2016-07-22 17:40:00
3 2016-07-22 20:31:00
4 2016-07-23 14:01:00
5 2016-07-23 19:24:00
6 2016-07-24 16:30:00
7 2016-08-01 16:00:00
8 2016-08-01 19:49:00
check dtype again:
In [72]: df.dtypes
Out[72]:
d datetime64[ns]
dtype: object
Upvotes: 1
Reputation: 78546
What you have is not a valid syntax for defining a Python variable. You should wrap with ''
or ""
to make it a string:
a = "1 / 22 / 2016 15:03"
dateconv1(a)
Upvotes: 0