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
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.
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.
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.
Just use the .dt
accessor and .days
attribute on the timedeltas.
df.days_from = df.days_from.dt.days
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With