How to convert time into seconds python? - python

Hello I am using the daytime module in python 3.3 to takeaway two times like this:
time_format = '%H:%M:%S'
total_time = datetime.strptime(time_left_system, time_format) - datetime.strptime(time_entered_system, time_format)
how would i convert this into seconds so i could print it like this?: 60 mph
Thanks

You are going to want to use the timedelta type from the datetime module, timedelta.total_seconds() will give you the time elapsed in seconds. you already have a timedelta by subtracting one datetime from the other, so you are set for the next step.From there I don't know how you are converting it to mph, probably you are measuring against a fixed distance, just like people on the race track calculate with chronometers given the seconds a car took in a set track distance, but since you don't give the info on how you convert it I can't help you on that part.

Related

Calculating time difference in 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)

Python: date time difference giving incorrect result

I have written a simple code to check if the time difference between 2 date timestamps is more than 7 days, which comes to 604,800 seconds.
If the time in seconds is more than 604,800 then it should print "Relax you have time!!!"
Please find my code below:
import time, datetime, sys, os
start_time = time.time()
from datetime import datetime, timedelta, date
from dateutil.parser import *
datetime1="2018-07-13 03:30:00"
datetime2="2018-07-20 04:30:00"
datetime2=datetime.strptime(datetime2, "%Y-%m-%d %H:%M:%S").date() # this is to convert it into a datetime object
datetime1=datetime.strptime(datetime1, "%Y-%m-%d %H:%M:%S").date() # this is to convert it into a datetime object
difference1 =(datetime2-datetime1).total_seconds()
print("the difference in seconds is "+str(difference1))
if difference1 > 604800: #if the difference is more than 7 days, relax , else start preparing
print("Relax you have time!!!")
else:
print("You need to start preparing!!!!!")
Problem:
The code somehow calculates the time in seconds to be more than 604800 only if I change the "datetime2" to "2018-07-21" which means that it is calculating the difference in rounded-off days and not seconds and then simply converting the rounded-off days into seconds, giving the incorrect answer.
For example, in the above code, since "datetime2" is in reality away from "datetime1" by more than 604,800 seconds(to be precise it is 608,400 seconds away), the output should be "Relax you have time!!!", but we get a different output.
What have I done to solve this?
Till now I have looked at similar questions:
How do I check the difference, in seconds, between two dates? (did not work for me as I got TypeError: an integer is required (got type datetime.date))
and
Time difference in seconds (as a floating point) (this caters to only very tiny time differences and does not capture a scenario when user enters timestamps himself)
and
How to calculate the time interval between two time strings (this is what I have done in my code, but it does not work as expected)
Can you please suggest the problem in my code?
UPDATE: Thanks to #Tim Peters for pointing out that .date() discards the hours,mins and seconds.
I only needed to discard .date() for it to work correctly.
In this case the issue is that you create two datetime.datetime objects with strptime and immediately truncate them to datetime.date objects, which don't have the time components (hours, minutes, seconds, microseconds, tzinfo), so you get two calendar dates which are exactly 7 days apart.
You can fix your original code like this:
from datetime import datetime, timedelta
datetime1 = "2018-07-13 03:30:00"
datetime2 = "2018-07-20 04:30:00"
# The following creates two datetime.datetime objects
datetime2 = datetime.strptime(datetime2, "%Y-%m-%d %H:%M:%S")
datetime1 = datetime.strptime(datetime1, "%Y-%m-%d %H:%M:%S")
difference1 =(datetime2-datetime1).total_seconds()
print("the difference in seconds is "+str(difference1))
# if the difference is more than 7 days, relax , else start preparing
if difference1 > 604800:
print("Relax you have time!!!")
else:
print("You need to start preparing!!!!!")
But one additional thing to note is that datetime.timedelta objects can be directly compared, so you do not need to calculate the number of seconds, so you can change that part to avoid the "number of seconds" calculation (and your intention is clearer):
difference1 = datetime2 - datetime1
# if the difference is more than 7 days, relax , else start preparing
if difference1 > timedelta(days=7):
I imagine that in reality you are not constructing the datetime.datetime objects from string literals as you have in this example, but in case you are, I would also note that you can directly construct those literals as well, so with that refactoring in place, here's how I would have written your example:
from datetime import datetime, timedelta
# The following creates two datetime.datetime objects
datetime1 = datetime(2018, 7, 13, 3, 30)
datetime2 = datetime(2018, 7, 20, 4, 30)
difference1 = datetime2 - datetime1
# if the difference is more than 7 days, relax , else start preparing
if difference1 > timedelta(days=7):
print("Relax you have time!!!")
else:
print("You need to start preparing!!!!!")

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)

Calculate time after X hours?

For example, if the start time is 8:00am how do I calculate the time after 20 hours have passed?
Need to use something like timedelta
from datetime import datetime, timedelta
twenty_hours= datetime.now() + timedelta(hours=20)
ofcourse you'll change datetime.now() to your 8am or what ever time you wish
>>> format(twenty_hours, '%H:%M:%S')
'23:24:31'
There are at least two possible interpretations of your question:
Find the local time that is exactly 20 hours from now:
#!/usr/bin/env python3
from datetime import datetime, timedelta, timezone
now = datetime.now(timezone.utc) # current time in UTC
in20hours = (now + timedelta(hours=20)).astimezone() # local time in 20 hours
print("Local time in 20 hours: {in20hours:%I:%M %p}".format(**vars())) # AM/PM
Find the time while ignoring any changes in the local UTC offset (due to DST transitions or any other reason):
#!/usr/bin/env python
from datetime import datetime, timedelta, timezone
now = datetime.now() # local time
by20hours = now + timedelta(hours=20) # move clock by 20 hours
print("Move clock by 20 hours: {by20hours:%I:%M %p}".format(**vars())) # AM/PM
Related: python time + timedelta equivalent
Both methods produce the same result if the local utc offset won't change during the next 20 hours. Otherwise the second method fails, to find the time after 20 hours have passed.
You might need the second method if you want to do something at the same local time no matter how many hours have passed in between e.g., if you want to get up at 6am no matter whether 24 hours have passed or not. See How can I subtract a day from a Python date?
More details on the time arithmetics if you are working with local time see at Find if 24 hrs have passed between datetimes - Python.

Convert string to time format

>>> x
['00:05:09.252', '00:05:42.244', '00:06:44.546']
How can I convert these string items to 'hh:mm:ss.uuu' time format, so that I can do time calculations in this format?
I read the docs, but everything seem to be explained in context of datetime and various time zones, while I just wanna do calculation in time format without writting my own function for this task.
given your data is strictly formatted to hour:min:sec.usec
(looks like they don't have directives to deal with microseconds in python strptime, so guess you have to supply the values yourself to datetime.time's constructor)
import datetime
def timeconverter(timestring):
hour, min, sec = timestring.split(':')
sec, usec = sec.split('.')
time = datetime.time(*[int(x, 10) for x in (hour, min, sec, usec)])
return time
Check out strptime in the time module.
import time
t= time.strptime("00:05:42.244", "%H:%M:%S")
Do this if you don't care about the decimal part of the seconds. If you do care then the approuch used by thkang is a better solution.

Categories

Resources