6 examples of 'python calculate time difference' in Python

Every line of 'python calculate time difference' code snippets is scanned for vulnerabilities by our powerful machine learning engine that combs millions of open source libraries, ensuring your Python code is secure.

All examples are scanned by Snyk Code

By copying the Snyk Code Snippets you agree to
this disclaimer
27def compute_time(is_hourly):
28 """Figure out the proper start and end time"""
29 utcnow = datetime.datetime.utcnow().replace(tzinfo=pytz.utc)
30 utcnow = utcnow.replace(minute=0, second=0, microsecond=0)
31
32 if is_hourly:
33 lasthour = utcnow - datetime.timedelta(minutes=60)
34 sts = lasthour.replace(minute=0)
35 ets = lasthour.replace(minute=59)
36 else:
37 yesterday = utcnow - datetime.timedelta(hours=24)
38 sts = yesterday.replace(hour=0)
39 ets = sts.replace(hour=23, minute=59)
40 return sts, ets
Important

Use secure code every time

Secure your code as it's written. Use Snyk Code to scan source code in minutes – no build needed – and fix issues immediately. Enable Snyk Code

501def compute_timediff_seconds(time1_str, time2_str):
502 if re.match('\+[0-9][0-9]:[0-9][0-9]', time1_str[-6:]):
503 time1_str = time1_str[:-6]
504 time2_str = time2_str[:-6]
505 datetime1 = datetime.strptime(time1_str,
506 '%Y-%m-%dT%H:%M:%S.%f')
507 datetime2 = datetime.strptime(time2_str,
508 '%Y-%m-%dT%H:%M:%S.%f')
509 print("time difference {}".format((datetime2 - datetime1)))
510 diff = (datetime2 - datetime1).total_seconds()
511 return diff
83def time_difference_UTC(otherdate):
84 return humanize_date_difference(now=datetime.datetime.utcnow(),
85 otherdate=otherdate)
38def timediff(a, b):
39 delta = b - a
40 if hasattr(delta, 'total_seconds'):
41 return delta.total_seconds()
42 ret = abs(delta.days * 86400)
43 ret += abs(delta.seconds)
44 ret += abs(delta.microseconds / 1000000.0)
45 if b < a:
46 return -ret
47 return ret
24@filters.app_template_filter("timediff")
25def timediff(time):
26 """Return the difference in seconds between now and the given time."""
27 now = datetime.datetime.utcnow()
28 diff = now - time
29 diff_sec = diff.total_seconds()
30 return diff_sec
102def get_rel_delta(self):
103 return relativedelta(years=self.time_obj.tm_year * self.defined_values[0],
104 months=self.time_obj.tm_mon * self.defined_values[1] - 1,
105 days=self.time_obj.tm_mday * self.defined_values[2],
106 hours=self.time_obj.tm_hour * self.defined_values[3],
107 minutes=self.time_obj.tm_min * self.defined_values[4],
108 seconds=self.time_obj.tm_sec * self.defined_values[5]).normalized()

Related snippets