Calculating time difference in python - python

I want to make a code in python to find out the duration an employee had worked by taking two inputs.
input1 will be the time when the employee arrived at work, in hh:mm format.
input2 will be the time when the employee left work, in hh:mm format.
I want to calculate the duration an employee worked in hh:mm format when I subtract input1 from input2.
Please help in making this code.

There is no timedelta attribute for time objects.
You can use a datetime object first, then do:
difference = datetime1 - datetime2
The, finally, do:
print(difference.strftime('%H:%M')
Alternatively, if you are only allowed to use time input/object, you can do:
import datetime
# Time in example
a = datetime.time(9, 30)
# Time out example
b = datetime.time(17, 45)
hours = abs(int(b.strftime('%H')) - int(a.strftime('%H')))
minutes = abs(int(b.strftime('%M')) - int(a.strftime('%M')))
time_difference = datetime.time(hours, minutes)
print(time_difference)

Related

How to Split a substract of a date in python

My code is the following:
date = datetime.datetime.now()- datetime.datetime.now()
print date
h, m , s = str(date).split(':')
When I print h the result is:
-1 day, 23
How do I get only the hour (the 23) from the substract using datetime?
Thanks.
If you subtract the current date from a past date, you would get a negative timedelta value.
You can get the seconds with td.seconds and corresponding hour value via just dividing by 3600.
from datetime import datetime
import time
date1 = datetime.now()
time.sleep(3)
date2 = datetime.now()
# timedelta object
td = date2 - date1
print(td.days, td.seconds // 3600, td.seconds)
# 0 0 3
You're not too far off but you should just ask your question as opposed to a question with a "real scenario" later as those are often two very different questions. That way you get an answer to your actual question.
All that said, rather than going through a lot of hoop-jumping with splitting the datetime object, assigning it to a variable which you then later use look for what you need in, it's better to just know what DateTime can do since that can be such a common part of your coding. You would also do well to look at timedelta (which is part of datetime) and if you use pandas, timestamp.
from datetime import datetime
date = datetime.now()
print(date)
print(date.hour)
I can get you the hour of datetime.datetime.now()
You could try indexing a list of a string of datetime.datetime.now():
print(list(str(datetime.datetime.now()))[11] + list(str(datetime.datetime.now()))[12])
Output (in my case when tested):
09
Hope I am of help!

Subtract Time from Datetime Field in Django/Python

This question seems obvious and easy but I am getting my head stretched out here. Problem is I have datetime field in model and I want to subtract time from another attribute.
here is my code I have tried so far.
#property
def boarding_time(self):
print('---------------------------')
time = self.schedule.travel_date_time.time()
print()
time_added = self.schedule.bus_company_route.routeboardingpoint_set.get(
point=self.boarding_point
).time_added
time1 = timedelta(hours=time.hour, minutes=time.minute, seconds=time.second)
time2 = timedelta(hours=time_added.hour, minutes=time_added.minute, seconds=time_added.second)
return (time1-time2)
I am actually trying to find the time delay the vehicle reaches to certain destination. Suppose vehicle was supposed to move at 8 am but the vehicle departed from bus park at 8:15 am and passenger waiting will have 15 min added to their location but I am getting error as
'datetime.timedelta' object has no attribute 'isoformat'
Im not sure if this answers your question but you can try:
from datetime import datetime, date
datetime.combine(date.today(), exit) - datetime.combine(date.today(), enter)
combine builds a datetime, that can be subtracted. Your can google about it for more...
https://docs.python.org/3/library/datetime.html
At a high level, the adjusted boarding time is derived from taking scheduled boarding time and adding to it the amount of time that lapsed between the scheduled departure time and the actual departure time from the previous destination.
Here is a simplified example that hopefully illustrates the key concepts to help you piece together a solution for your more complex problem:
from datetime import datetime, timedelta
scheduled_boarding_time = datetime.fromisoformat("2021-01-12T10:00")
departure_delay_in_minutes = 15
adjusted_boarding_time = scheduled_boarding_time + timedelta(minutes=delay_in_minutes)
print(adjusted_boarding_time.isoformat())
2021-01-12T10:15:00
The solution to your question lies in the way you handle the time stamp format. You have your date time in AM/PM for this you have to format you date accordingly. Here is something what you can do instead of what you are doing right now
from datetime import datetime
time = '2021/1/13 8:15 am' #your date format
time_added = '2021/1/13 8:45 am' #your date format
format = '%Y/%m/%d %H:%M %p' #will format your date for further computation
time = datetime.strptime(time, format)
time
o/p
datetime.datetime(2021, 1, 13, 8, 15)
time_added = datetime.strptime(time_added, format)
time_added
o/p
datetime.datetime(2021, 1, 13, 8, 45)
time2 = time_added-time1 # this will give you time difference in seconds
divmod(time2.total_seconds(), 60)[0] #use this to get difference in minutes
o/p
30.0
This same you return in your function and it will solve your problem

Datetime formatting

The api I am working with gives time is the following format when I place an order.
'orderDateTime': '12-May-2020 14:54:11'
What I am looking to do is to find the number of minutes/seconds that have passed since I placed the order. So if it has already been for example 10 minutes, if I would like to cancel or modify the order I can do it.
I have tried everything I know to convert the given time format to do what I want but have been unsuccessful. Please help. Thanks in advance.
time_now = datetime.now()
print("Time now is",time_now)
t1 = time_now.strftime("%d-%b-%Y %H:%M:%S")
print(t1)
trade_time = datetime(12-May-2020 15:01:32)
t2 = datetime.strftime(trade_time,"%d-%b-%Y %H:%M:%S")
print(t2)
You are mixing the datetime objects and their representation as strings.
What you need to do is convert your trade time to a datetime object, by using the strptime method. strftime does the opposite, it produces a formatted text representation of your datetime.
Then, you can subtract the two datetime objects, which will give you the difference as a timedelta, from which you can get the difference as a number of seconds.
So, your code should look like:
from datetime import datetime
time_now = datetime.now()
trade_time_as_str = '12-May-2020 15:01:32'
trade_time = datetime.strptime(trade_time_as_str,"%d-%b-%Y %H:%M:%S")
elapsed = time_now - trade_time
elapsed_seconds = elapsed.total_seconds()
print(elapsed_seconds)
# 15808.77104

Real Time Clock(RTC) in Python

I am a beginner in Python. I am wondering about does Python has Real Time Clock which is giving us exactly year, month, day, hour, min, and second?
Thank you for your help!
For Date Time operations in python you need to import datetime library.There different functions related to date formatting, getting current date and time etc.. Refer this documentation
import datetime
now = datetime.datetime.now()
print ("Current date and time : ")
print (now.strftime("%Y-%m-%d %H:%M:%S"))
Hope the above code will do your job ...
datetime.now()
Thats it.It gives the current date and time upto microseconds.
Use as you want.
Setting an alarm after 2 days.
alarm_time = date.today() + timedelta(days = 2) #set alarm time 2day after today
while(date.today()!=alarm_time): #run loop till datetoday is not alarm_time
time.sleep(60*60) #wait for an hour then recheck time
#do here anything you want to do when alarm time has reached#
you can try this:
temp.year, temp.month, temp.day,temp.hour,temp.minute,temp.second would give your desire values separately
from datetime import datetime
temp = datetime.now()
timee = "{:04d}{:02d}{:02d} {:02d}:{:02d}:{:02d}".format(temp.year, temp.month, temp.day,temp.hour,temp.minute,temp.second)

Python - difference between time

Looking for easiest way to calculate the difference between 2 python times and display the millisecond delta
I have 2 times
startTime = datetime.datetime.now().time()
do some stuff...
endTime= datetime.datetime.now().time()
This works fine and when I log the times out and I get something like this in my logs...
RequestStartTime = 08:56:19.188999
ResponseTime = 08:56:19.905999
When I try to simply subtract them like this
delta = endTime - startTime
I get the following error
unsupported operand type(s) for -: 'time' and 'time'
All I want to do is show the difference in microseconds and I can't figure it out
I want to show is 717000 ms
If you just use the result of now(), and don't convert them to times, you can take the difference & extract the bits you want in the form you want; for example:
startTime = datetime.datetime.now()
endTime= datetime.datetime.now()
delta = endTime - startTime
print str(delta).split(":")[2]
Try this:
from datetime import datetime, date
datetime.combine(date.today(), endTime) - datetime.combine(date.today(), startTime)
Hope this Helps.
To measure the difference manually, you should use time.monotonic() instead.
If you don't care about leap seconds (~1s error once per year and a half) and you need to display the local time:
#!/usr/bin/env python3
from datetime import datetime, timedelta, timezone
start = datetime.now(timezone.utc).astimezone() # current local time
# print("RequestStartTime = %s" % start.time())
end = datetime.now(timezone.utc).astimezone()
diff_milliseconds = (end - start) / timedelta(milliseconds=1)
print("%.0f ms" % diff_milliseconds)
The code works fine around/during DST transitions.
Note: it is different from the code that uses just .now(). If you use .now() (no argument) then you get a naive datetime object that represents local time and in that case if a DST transition happens between start and end times then end - start returns a completely wrong result i.e., the code may be wrong by an hour approximately couple of times per year in some timezones.
the reason why you are getting an error is because class time does not support subtraction. You must turn time into miliseconds (int format) to subtract from one another.
instead of using datetime, use time
import time
def timenow():
return int(round(time.time() * 1000))
startTime = timenow()
time.sleep(1)
endTime = timenow()
delta = endTime - startTime
print delta
The simplest solution would be to convert the datetime objects to timestamps and subtract those. If you use Python 3.3 or later you can simply do something along these lines
startTime = datetime.datetime.now(timezone.utc).timestamp()
...
endTime = datetime.datetime.now(timezone.utc).timestamp()
Then you can just subtract those.
In Python 2 you do not have the timestamp method available. One way around would be to use a timedelta object:
startTime = datetime.datetime.now(timezone.utc)
...
endTime = datetime.datetime.now(timezone.utc)
dt = (endTime - startTime).total_seconds()
A third option is to simply use raw timestamps with time.time() and subtract them to get the time interval in seconds and fraction of seconds.
To be extra safe you could use time.monotonic() as #Sebastian mentions.
This is the best answer for this problem:
https://stackoverflow.com/a/39651061/2686243
from datetime import datetime, date
duration = datetime.combine(date.min, end) - datetime.combine(date.min, beginning)

Categories

Resources