Tom
Tom

Reputation: 551

Python: convert datedelta to int value of time difference

I want to change time delta to integer value .

My code is as below.

import datetime
now = datetime.date.today()
print(now.toordinal()) # 736570
cali_date = datetime.data(2017, 6, 14)
print(cali_date.toordinal()) # 736494
date1 = now - cali_date
print(date1) # 76 days, 0:00:00

But, I want to get just 76 with integer. How can I solve this problem? Thank you.

Upvotes: 17

Views: 54568

Answers (5)

Riekezoe
Riekezoe

Reputation: 11

For me, none of the solutions above worked fully. After I made sure both of the dates had the datetime format, their difference now also has the datetime format. Afterwards using .days works as intended.

date1 = pd.to_datetime(now) - pd.to_datetime(cali_date) 
print(date1) # 2179 days 00:00:00
date1  = date1.days 
print(date1) #2179

Upvotes: 0

carsalves
carsalves

Reputation: 9

Just set a new variable:

date1 = now - cali_date
date_int = date1

print(type(date_int))
# <class 'int'>

Upvotes: 0

Marta
Marta

Reputation: 71

For me worked using Serie.dt.days . It changes the datatype of a Serie from "timedelta" to "int" and the time difference is presented in full days.

Upvotes: 1

jsbueno
jsbueno

Reputation: 110311

date1 is a timedelta object - use date1.days to get the number of days as an integer, or date1.total_seconds() to see the number of seconds between the two datetime objects.

Upvotes: 10

Martijn Pieters
Martijn Pieters

Reputation: 1122262

Just reference the days attribute of the timedelta object you have there:

print(date1.days)

There are also timedelta.seconds and timedelta.microseconds attributes, modeling the complete delta state.

Upvotes: 30

Related Questions