Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)?

like image 998
user2823030 Avatar asked Jul 02 '26 09:07

user2823030


2 Answers

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.

like image 133
jfs Avatar answered Jul 03 '26 21:07

jfs


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

like image 43
minocha Avatar answered Jul 03 '26 23:07

minocha



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!