user2823030
user2823030

Reputation: 109

Determine seconds between two dates in Python

I'm calling the Office 365 Calendar API and receiving the start date of the event back in the following format:

2016-05-20T08:00:00Z

I want to check when an event is near e.g. 5 minutes time, and use something along the lines of the following solution: [Python - Do (something) when event is near

What's the best way of determining the number of seconds between my event in the date/time format above and the current time now (in UTC taking into account daylight savings)?

Upvotes: 3

Views: 9103

Answers (3)

jfs
jfs

Reputation: 414305

Here's stdlib-only solution (combination of @tschale's and @minocha's answers):

#!/usr/bin/env python
from datetime import datetime, timedelta

then = datetime.strptime('2016-05-20T08:00:00Z', '%Y-%m-%dT%H:%M:%SZ')
now = datetime.utcnow()
if abs(now - then) < timedelta(minutes=5):
    "within 5 minutes"

Related: Find if 24 hrs have passed between datetimes.

Upvotes: 4

tschale
tschale

Reputation: 975

In python there is the datetime module. You can use pytz to get a timezone specific now-time. However, if you can you should work with UTC time and only convert it to the local time for output to be read by humans.

from datetime import datetime
import pytz
time = '2016-05-20T08:00:00Z'
formatted_time = datetime.strptime(time, '%Y-%m-%dT%H:%M:%SZ')
tz = pytz.timezone('Europe/Berlin')
time_now = datetime.now(tz)
time_delta = formatted_time - time_now()
delta_in_seconds = time_delta.total_seconds()

The format parameters for datetime.strptime are specified datetime.strftime

Upvotes: 1

minocha
minocha

Reputation: 1044

The time you get needs to be cnoverted to datetime format -

>>import datetime
>>import iso8601
>>datetime_variable = iso8601.parse_date('2016-05-20T08:00:00Z')
>>(datetime.replace(tzinfo=None) - datetime.datetime.utcnow()).seconds
>>56086

You can do this if the response always contains the timezone as 'Z' which translates to UTC. since the normal datetime.datetime object is timezone naive you have to strip the other object of the tzinfo too, but this shouldn't be a problem since both are in UTC.

Hope this works

Upvotes: 3

Related Questions