Harish reddy
Harish reddy

Reputation: 431

converting integer to datetime values pandas

I have a column with datetime and integer values..However i want to convert even the integer values to datetikme as well.

StartTime             EndTime               Source 
2170-01-01 00:00:00   2170-01-01 00:00:00   NA
1.60405e+18           1.60405e+18           Arm_dearm

I tried using

pd.to_datetime(site_list['StartTime'])

but it yields the same result.

And Ultimately i am not able to run the following line.

np.where(site_list["StartTime"].dt.date!=site_list["EndTime"].dt.date,"armed next day",site_list["Source"])

which throws the following error:

mixed datetimes and integers in passed array

Upvotes: 0

Views: 671

Answers (1)

StealthBadger747
StealthBadger747

Reputation: 83

The issue as the error states is that there are mixed types in the columns so it will not convert it. I'm going to assume it is a UNIX timestamp. Check this answer and see if maybe this is the time format you are dealing with.

We can get around this by doing something like this:

import datetime
def convert(time):
    return datetime.datetime.fromtimestamp(time)

site_list["StartTime"] = site_list["StartTime"].apply(lambda x: convert(x) if isinstance(x, int) else x)

This will check each value in the StartTime column, then check if it is a integer or not. If it is then it will convert it to the datetime type. If is not a integer it will leave it alone.

Upvotes: 1

Related Questions