Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pandas - Converting Derived Datetime to Integer

Tags:

python

pandas

I have a pandas dataframe, 'df', where there is an original column with dates in datetime format. I set a hard date as a variable:

 hard_date = datetime.date(2013, 5, 2)

I then created a new column in my df with the difference between the values in the date column and the hard_date...

df['days_from'] = df['date'] - hard_date

This produced a good output. for instance, when I print the first cell in the new column it shows:

print (df['days_from'].iloc[0])

28 days 00:00:00

But now I want to convert the new column to just the number of days as an integer. I thought about just taking the first 2 characters, but many of the values are negative, so I am seeking a better route.

Any thoughts on an efficient way to convert the column to just the integer of the days?

Thanks

like image 538
Jeff Saltfist Avatar asked Feb 13 '17 23:02

Jeff Saltfist


People also ask

How do I convert datetime to int in Python?

strftime() object. In this method, we are using strftime() function of datetime class which converts it into the string which can be converted to an integer using the int() function.

How do I convert a timestamp to a number in Python?

Example 1: Integer timestamp of the current date and timeConvert the DateTime object into timestamp using DateTime. timestamp() method. We will get the timestamp in seconds. And then round off the timestamp and explicitly typecast the floating-point number into an integer to get the integer timestamp in seconds.

What is pandas datetime format?

The date-time default format is “YYYY-MM-DD”. Hence, December 8, 2020, in the date format will be presented as “2020-12-08”. The datetime format can be changed and by changing we mean changing the sequence and style of the format.


1 Answers

Just use the .dt accessor and .days attribute on the timedeltas.

df.days_from = df.days_from.dt.days
like image 116
miradulo Avatar answered Oct 22 '22 23:10

miradulo