1

how to get the unit by differencing in 2 datetime.

i.e.,

datetime1 = 2020-06-29 16:15:27, datetime2 = 2020-06-29 16:17:27

unit = minute

datetime1 = 2020-06-29 16:15:27, datetime2 = 2020-06-29 17:17:27

unit = hour

datetime1 = 2020-06-29 16:15:27, datetime2 = 2020-06-31 17:17:27

unit = day

datetime1 = 2020-06-29 16:15:27, datetime2 = 2020-07-29 17:17:27

unit = month

Alexander
  • 16,091
  • 5
  • 13
  • 29

5 Answers5

1

For the days, hours and minutes, you can have the foolowing approach:

Days

import datetime
  
a = datetime.datetime(2017, 6, 21, 18, 25, 30)
b = datetime.datetime(2017, 5, 16, 8, 21, 10)
  
ts_start=a
ts_end=b
ts_diff=ts_end-ts_start
secs=ts_diff.total_seconds()
days,secs=divmod(secs,secs_per_day:=60*60*24)

answer='Duration={} days'.format(int(days))

Hours

import datetime
  
a = datetime.datetime(2017, 6, 21, 18, 25, 30)
b = datetime.datetime(2017, 5, 16, 8, 21, 10)
  
ts_start=a
ts_end=b
ts_diff=ts_end-ts_start
secs=ts_diff.total_seconds()

hrs,secs=divmod(secs,secs_per_hr:=60*60)

answer='Duration={} hrs'.format(int(hrs))

Minutes

import datetime
  
a = datetime.datetime(2017, 6, 21, 18, 25, 30)
b = datetime.datetime(2017, 5, 16, 8, 21, 10)
  
ts_start=a
ts_end=b
ts_diff=ts_end-ts_start
secs=ts_diff.total_seconds()
mins,secs=divmod(secs,secs_per_min:=60)
answer='Duration={} mins'.format(int(mins))

seconds

import datetime
  
a = datetime.datetime(2017, 6, 21, 18, 25, 30)
b = datetime.datetime(2017, 5, 16, 8, 21, 10)
  
ts_start=a
ts_end=b
ts_diff=ts_end-ts_start
secs=ts_diff.total_seconds()



answer='Duration={} secs'.format(int(secs))

As for months, it is a little trickier. The best way to do this is given here Best way to find the months between two dates

1

Create Enum to store the difference between two datetime objects

#!/usr/bin/env python3.10

from datetime import datetime
from enum import Enum, auto, unique

@unique
class DATETIME_UNIT(Enum):

    YEAR = auto()
    MONTH = auto()
    DAY = auto()
    HOUR = auto()
    MINUTE = auto()
    SECOND = auto()
    SAME = auto()

def getDateTimeUnit(datetime1:datetime, datetime2:datetime):
    unit = DATETIME_UNIT.SAME

    if datetime1.year != datetime2.year:
        unit = DATETIME_UNIT.YEAR
    elif datetime1.month != datetime2.month:
        unit = DATETIME_UNIT.YEAR
    elif datetime1.day != datetime2.day:
        unit = DATETIME_UNIT.DAY
    elif datetime1.hour != datetime2.hour:
        unit = DATETIME_UNIT.HOUR
    elif datetime1.minute != datetime2.minute:
        unit = DATETIME_UNIT.MINUTE
    elif datetime1.second != datetime2.second:
        unit = DATETIME_UNIT.SECOND
    else:
        unit = DATETIME_UNIT.SAME

    return unit

if __name__ == "__main__":
    #datetime1 = datetime.strftime("2020-06-29 16:15:27", "%yyy-%mm-%dd")
    #datetime1 = datetime.strptime("2020-06-29 16:15:27", "%Y-%m-%d %H:%M:%S")
    #print(datetime1)
    #print(datetime1.year)
    #print(getDateTimeUnit(datetime1, datetime1))

    datetime1 = datetime.strptime("2020-06-29 16:15:27", "%Y-%m-%d %H:%M:%S")
    datetime2 = datetime.strptime("2020-06-29 16:17:27", "%Y-%m-%d %H:%M:%S")
    print(getDateTimeUnit(datetime1, datetime2))#MINUTE

    datetime1 = datetime.strptime("2020-06-29 16:15:27", "%Y-%m-%d %H:%M:%S")
    datetime2 = datetime.strptime("2020-06-29 17:17:27", "%Y-%m-%d %H:%M:%S")
    print(getDateTimeUnit(datetime1, datetime2))#HOUR

    datetime1 = datetime.strptime("2020-06-29 16:15:27", "%Y-%m-%d %H:%M:%S")
    datetime2 = datetime.strptime("2020-06-30 17:17:27", "%Y-%m-%d %H:%M:%S")
    print(getDateTimeUnit(datetime1, datetime2))#DAY

    datetime1 = datetime.strptime("2020-06-29 16:15:27", "%Y-%m-%d %H:%M:%S")
    datetime2 = datetime.strptime("2020-07-29 17:17:27", "%Y-%m-%d %H:%M:%S")
    print(getDateTimeUnit(datetime1, datetime2))#YEAR
Udesh
  • 2,415
  • 2
  • 22
  • 32
1

In python we can directly subtract datetime object using - operator

example

import datetime
  
# datetime(year, month, day, hour, minute, second)
a = datetime.datetime(2021, 6, 21, 18, 25, 30)
b = datetime.datetime(2020, 5, 16, 8, 21, 10)
  
# returns a timedelta object
c = a-b 
print('Difference: ', c)
  
minutes = c.total_seconds() / 60
hours = c.total_seconds()//3600
months = (a.year - b.year) * 12 + (a.month - b.month)
days = c.days
  
0

datetime supports "-" operations and if you want other unit, then seconds just convert it by simple division

from datetime import datetime

datetime1 = datetime.fromisoformat("2020-06-29 16:15:27")
datetime2 = datetime.fromisoformat("2020-06-29 16:17:27")
delta = datetime2 - datetime1
print(delta.seconds)
Grekkq
  • 679
  • 6
  • 14
0

Using the datetime module in python stdlib we can create a function that generates the difference in seconds and then divide to get the correct unit.

import datetime

def get_delta(dt1, dt2):
    datetimes = []
    for dt in [dt1, dt2]:
        date, time = dt.split(" ") # seperate date and time

        lst = [date.split("-"), time.split(":")] 

        # convert list to a `datetime` object
        dt = datetime.datetime(*[int(j) for i in lst for j in i])
        datetimes.append(dt)

    # return the delta in seconds
    return (datetimes[1] - datetimes[0]).seconds


datetime1 = "2020-06-29 16:15:27"
datetime2 = "2020-06-29 16:17:27"

seconds = get_delta(datetime1, datetime2)
minutes = seconds / 60
hours = seconds / (60*60)
days = seconds / (60*60*24)

For more details on the datetime module, here is a link to the python docs:

https://docs.python.org/3/library/datetime.html

Alexander
  • 16,091
  • 5
  • 13
  • 29