Link to home
Start Free TrialLog in
Avatar of Ravi soni
Ravi soni

asked on

Time difference between two datetime

how to calculate the time difference between date-time have single field only in python. it is like :-i have one row and column which field name is puch time here is the list of date-time 07/13/2017 18:41:24,       07/13/2017 18:57:31, 07/13/2017 17:29:27 now calculate time between 07/13/2017 18:41:24,       07/13/2017 18:57:31 in a and 07/13/2017 18:57:31, 07/13/2017 17:29:27  in b.
Avatar of gelonida
gelonida
Flag of France image

The standard module for dealing with dates/times and time deltas is datetime

you parse the  date timestrings into datetime objects, then you can calculate the difference and you receive a timedelta object.

In below example I will try to use as little 'tricks' as possible, so no list comprehensions, zip() functions.

import datetime
datetime_strings = [ "07/13/2017 18:41:24",     "07/13/2017 18:57:31",  "07/13/2017 17:29:27" ]

datetime_objects = []
for dtstring in datetime_strings:
    datetime_objects.append( datetime.datetime.strptime(dtstring, "%m/%d/%Y %H:%M:%S") )

timedeltas = []
for idx in range(len(datetime_objects)-1):
    timedeltas.append(datetime_objects[idx + 1] - datetime_objects[idx])

for delta in timedeltas:
    print("time delta is %s" % delta)

Open in new window


The output should be:
time delta is 0:16:07
time delta is -1 day, 22:31:56

Open in new window

Avatar of Ravi Soni
Ravi Soni

Here, i want only hours and minutes and i am asking how to store their difference in separate fields.. suppose, i have 4(in,out,in,out) datetime and two fields working hours and break hours. now i want difference of (in out,out in,in out = this in working hours field) and (difference of out in = this in break hours).
well your example just contained thee values and not four.

so you want to calculate the four delta values

import datetime
# just some example values 
datetime_strings = [ 
    "07/13/2017 18:41:24",     
    "07/13/2017 18:57:31",  
    "07/13/2017 19:29:27",  
    "07/13/2017 20:39:21",
     ]


print("input times are:\n - " + "\n - ".join(datetime_strings))
datetime_objects = []
for dtstring in datetime_strings:
    datetime_objects.append( datetime.datetime.strptime(dtstring, "%m/%d/%Y %H:%M:%S") )

timedeltas = []
for idx in range(len(datetime_objects)-1):
    timedeltas.append(datetime_objects[idx + 1] - datetime_objects[idx])

for delta in timedeltas:
    hours, seconds = divmod(delta.seconds, 3600)
    hours += 24 * delta.days
    minutes = int(seconds / 60)
    print("time delta is %s or %2d hours and %2d minutes" % (delta, hours, minutes))

Open in new window

Avatar of Ravi soni

ASKER

Its not about 3 or 4 delta values it may contain infinite values, dats my question... like ["07/13/2017 18:41:24",     "07/13/2017 18:57:31",  "07/13/2017 17:29:27"......etc many values].
Above code handles any amount of datetime_fields n and will generate n-1 delta values.

It also converts the datetime.timedelta object into hours and minutes (truncated, but rounding can be implemented as well)

you can sum up all the in / out times and display them with following code:

import datetime
import operator

# just some example values 
datetime_strings = [
    "07/13/2017 18:41:24",
    "07/13/2017 18:57:31",
    "07/13/2017 19:29:27",
    "07/13/2017 20:39:21",
     ]

# helper function to convert a time delta into an hour / minutes string
def time_delta_as_hour_string(delta):
    hours, seconds = divmod(delta.seconds, 3600)
    seconds += 30 # for rounding
    hours += 24 * delta.days
    minutes = int(seconds / 60)
    return "%02d:%02d" % (hours, minutes)

# alternative helper function with no rounding
#def time_delta_as_hour_string(delta):
#    return ':'.join(str(delta).split(':')[:2])

print("input times are:\n - " + "\n - ".join(datetime_strings))

# convert date time strings into date time objects
datetime_objects = []
for dtstring in datetime_strings:
    datetime_objects.append( datetime.datetime.strptime(dtstring, "%m/%d/%Y %H:%M:%S") )

# determine all deltas
timedeltas = []
for idx in range(len(datetime_objects)-1):
    timedeltas.append(datetime_objects[idx + 1] - datetime_objects[idx])

# show all deltas
for delta in timedeltas:
    print("delta %s %s" % (time_delta_as_hour_string(delta), delta))


# calculate in / out totals

# sum up every second value starting with the first value (index 0)
# to sum up timedeltas you cannot use the existing sum function it just works 
# for plain numbers reduce(operator.add, list_of_items) can sum up any list of
#  items, that have a '+' operator

# Her you calculate the 'precise' sum of time deltas 
# perhaps you wanted to round dwon to minutes before calculating the sum??

total_in_time = reduce(operator.add, (timedeltas[0::2]))

# sum up every second value starting with the secondvalue (index 1)
total_out_time = reduce(operator.add, (timedeltas[1::2]))

print("in total  %s" % (time_delta_as_hour_string(total_in_time)))
print("out total %s" % (time_delta_as_hour_string(total_out_time)))

Open in new window

so here can i take blank lis. then it works???
Normally it should also work with an empty list.

Just try it.
here out time come as it is...but the question is that when subtract (in,out,in) 2nd in -out then difference comes in break_works.
I don't undertstand:
just change datetime_strings to your desired values.

Run the script, copy/paste it's output to your answer and show which output you would have expected.

having sample data and expected values is the easiest way to make sure, that all participants really understand what you want/need.
This question needs an answer!
Become an EE member today
7 DAY FREE TRIAL
Members can start a 7-Day Free trial then enjoy unlimited access to the platform.
View membership options
or
Learn why we charge membership fees
We get it - no one likes a content blocker. Take one extra minute and find out why we block content.