3

I have a pandas 'Time' column which has values in the format 4/7/2013 of type string. I am trying to convert the entire column into datetime.datetime format. I used the following code-

df3['Date'] =  pd.to_datetime(df3['Date'],format='%m/%d/%Y') 

but after doing print(type(df3['Date'].iloc[0])) the type is coming <class 'pandas._libs.tslibs.timestamps.Timestamp'> but I wanted to convert it to datetime.datetime format.

What am I doing wrong?

I used this as reference-Convert Pandas Column to DateTime

ubuntu_noob
  • 2,305
  • 6
  • 23
  • 64
  • 1
    Nothing, this is pandas datetime drype. Is there some particular reason you don't want to use it? – juanpa.arrivillaga Jul 10 '18 at 15:21
  • I am doing subtraction in a loop with a data type datetime.datetime – ubuntu_noob Jul 10 '18 at 15:34
  • 1
    Are you trying to extract the date part? `pd.to_datetime(df3['Date'],format='%m/%d/%Y').dt.date` – ayhan Jul 10 '18 at 15:37
  • @user2285236 my column only has date like 4/7/2013 of type string – ubuntu_noob Jul 10 '18 at 15:46
  • 1
    Why are you doing subtraction in a loop? If you are going to do that, just use a list (or perhaps a map iterator) instead of a Dataframe. Pandas data structures are meant to be used with vectorised operations on primitive data types, not Python for loops with Python objects. This is the [XY problem](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem). Why don't you tell us what you are *really* trying to accomplish – juanpa.arrivillaga Jul 10 '18 at 16:17

2 Answers2

2

You can apply:

 YOUR_TARGET.to_pydatetime()

EXP:

 In [1]: type(pd.date_range('2018-01', '2020-05', freq='M')[0])
 Out[1]: pandas._libs.tslibs.timestamps.Timestamp


 In [62]: type(pd.date_range('2018-01', '2020-05', freq='M')[0].to_pydatetime())
 Out[62]: datetime.datetime

I think that is what you need right?

asmatrk
  • 237
  • 2
  • 9
0

From the Pandas documentation:

Return type depends on input:

list-like: DatetimeIndex

Series: Series of datetime64 dtype

scalar: Timestamp

So, to_timestamp returns a Pandas-style datetime object. There's really no benefit to converting to a datetime.datetimr object, but if you feel inclined to do so, you can convert the Pandas-style datetime object to a string, then use datetime.strptime to turn that string into a datetime.datetime object.

Community
  • 1
  • 1
Joel
  • 1,564
  • 7
  • 12
  • 20
  • I already have a column which has dates in the string format...I want to convert the rows in column to datetime.datetime – ubuntu_noob Jul 10 '18 at 15:35