Determining "days" in python when the timedelta.days is less than one

psxndc picture psxndc · Jan 31, 2013 · Viewed 54.9k times · Source

sorry in advance if this is dense. I am trying to find the days since I last posted a tweet. The problem I am running into is when the dates are different, e.g., today and yesterday, but not enough hours have passed to be a full "day."

# "created_at" is part of the Twitter API, returned as UTC time. The 
# timedelta here is to account for the fact I am on the west coast, USA 
lastTweetAt =  result.created_at + timedelta(hours=-8)

# get local time
rightNow = datetime.now()

# subtract the two datetimes (which gives me a timedelta)
dt = rightNow - lastTweetAt

# print the number of days difference
print dt.days

The problem is that if I posted a tweet at say 5 PM yesterday and am running the script at 8 AM today, only 15 hours have passed, which is 0 days. But obviously I want to say it's been 1 day since my last tweet if it was yesterday. And a kludge of adding "+1" isn't going to help because if I have tweeted today, I want the result to be 0.

Is there a better approach than using timedelta to get the difference?


Solution provided by Matti Lyra

The answer is to call .date() on the datetimes so they are converted to coarser date objects (without timestamps). The correct code looks like:

# "created_at" is part of the Twitter API, returned as UTC time.
# the -8 timedelta is to account for me being on the west coast, USA
lastTweetAt =  result.created_at + timedelta(hours=-8)

# get UTC time for right now
rightNow = datetime.now()

# truncate the datetimes to date objects (which have dates, but no timestamp)
# and subtract them (which gives me a timedelta)
dt = rightNow.date() - lastTweetAt.date()

# print the number of days difference
print dt.days

Answer

Matti Lyra picture Matti Lyra · Jan 31, 2013

You can use datetime.date() to compare the two dates (note: NOT dates with times), this truncates the datetime to have an resolution of days not hours.

...
# subtract the two datetimes (which gives me a timedelta)
dt = rightNow.date() - lastTweetAt.date()
...

The docs are always your friend

http://docs.python.org/2/library/datetime#datetime.datetime.date