Calculate time difference using Python

I am wondering if there is a way or a built-in library to find the time difference from entering two lines.

I mean, if I have 2 lines of input:

  • '2013-10-05T01: 21: 07Z
  • '2013-10-05T01: 21: 16Z

how can I calculate the time difference and print it as an output.

I know this sounds a little silly, but any help on this is appreciated.

+7
source share
3 answers

Parsing strings with strptime():

a = time.strptime('2013-10-05T01:21:07Z', '%Y-%m-%dT%H:%M:%SZ')
b = time.strptime('2013-10-05T01:21:16Z', '%Y-%m-%dT%H:%M:%SZ')

( (DST) ), - . - , DST (0), (1) (-1). float ( 1970-01-01):

a = time.mktime(a)
b = time.mktime(b)

( ):

d = b - a

///:

days = int(d) / 86400
hours = int(d) / 3600 % 24
minutes = int(d) / 60 % 60
seconds = int(d) % 60

, , a b; -)

@J.F.Sebastian , , . , UTC, . , DST. , , ( UTC DST).

, DST (-1) (, 0 ) :

a = time.mktime(a[:-1] + (0,))  # switch DST to off
b = time.mktime(b[:-1] + (0,))

, @J.F.Sebastian, time datetime.datetime, DST:

a = datetime.datetime.strptime('2013-10-05T01:21:07Z', '%Y-%m-%dT%H:%M:%SZ')
b = datetime.datetime.strptime('2013-10-05T01:21:16Z', '%Y-%m-%dT%H:%M:%SZ')

datetime , , timedelta, ​​ , . , 0:00:05, , .

+7

, ISO 8601 dateTime. , GPS eXchange.

[-]CCYY-MM-DDThh:mm:ss[Z|(+|-)hh:mm]

:

import datetime
a = datetime.datetime.strptime("2013-10-05T01:21:07Z", "%Y-%m-%dT%H:%M:%SZ")
b = datetime.datetime.strptime("2013-10-05T01:21:16Z", "%Y-%m-%dT%H:%M:%SZ")
c = b - a
print(c)

< > :

  • Python.
  • -

:

  • ISO 8601, '2013-10-05T01: 21:16 + 00: 00'
  • , '2012-06-30T23: 59: 60Z'

python-dateutil:

import dateutil.parser
a = dateutil.parser.parse("2013-10-05T01:21:07Z")
b = dateutil.parser.parse("2013-10-05T01:21:16Z")
c = b - a
print(c)

< > :

:

  • python-dateutil (pip install python-dateutil)
  • , '2012-06-30T23: 59: 60Z'

time.strptime time.mktime, Alfe

< > :

  • Python.
  • , '2012-06-30T23: 59: 60Z'

:

  • ISO 8601, '2013-10-05T01: 21:16 + 00: 00'
  • "2012-06-30T23: 59: 60Z" "2012-07-01T00: 00: 00Z" (, , )
+7
import datetime
a = datetime.datetime.now()
b = datetime.datetime.now()
c = b - a
datetime.timedelta(0, 8, 562000)
divmod(c.days * 86400 + c.seconds, 60)

Original answer here

-2
source

Source: https://habr.com/ru/post/1542147/


All Articles