Add/substract timedelta to imported time - python

I am importing two time values (format "%H:%M:%S") into this function and I would like to add/subtract a buffer (check_period, usually a value of 5) to it. The timedelta works fine on the time values created in this function, but not for imported values. Any suggestions on how I can fix this?
Many thanks,
VBA Pete
def check_shuttertime(close_time,open_time,check_period):
neg_adj_current_time = datetime.datetime.now() - datetime.timedelta(hours=0, minutes=check_period+1)
neg_adj_current_time = neg_adj_current_time.strftime("%H:%M:%S")
pos_adj_current_time = datetime.datetime.now() + datetime.timedelta(hours=0, minutes=check_period+1)
pos_adj_current_time = pos_adj_current_time.strftime("%H:%M:%S")
close_time = close_time + datetime.timedelta(hours=0, minutes=check_period+1) #<-ERRROR OCCURS HERE
open_time = open_time - datetime.timedelta(hours=0, minutes=check_period+1) #<-ERRROR OCCURS HERE
current_time = datetime.datetime.now().strftime("%H:%M:%S")

If close_time and open_time are of type strings you will get an error stating that the + operator between a string and timedelta is not supported:
TypeError: can only concatenate str (not "datetime.timedelta") to str
The way to fix this would be to parse the string into a datetime before applying the addition. E.g. as follows:
import datetime
close_time="11:22:33"
new_close_time = datetime.datetime.strptime(close_time, "%H:%M:%S") + datetime.timedelta(minutes=5)
print(new_close_time)
This would then yield:
1900-01-01 11:27:33

Related

Convert datetime object into a string

I need to convert a datetime into a string using numpy.
Is there another way to directly convert only one object to string that doesn't involve using the following function passing an array of 1 element (which returns an array too)?
numpy.datetime_as_string(arr, unit=None, timezone='naive', casting='same_kind')
With this function, I can make the conversion, but I just want to know if there is a more direct/clean way to do it.
Thanks in advance.
As we dont know what is inside of arr, I assume it is just datetime.now()
If so try this:
import datetime
datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')
>>> '2022-07-28 10:27:34.986848'
If you need numpy version:
np.array(datetime.datetime.now(), dtype='datetime64[s]')
>>> array('2022-07-28T10:32:19', dtype='datetime64[s]')
if you just want to convert one numpy DateTime64 object into a string, here is the answer.
import datetime
yourdt = yourdt.astype(datetime.datetime)
yourdt_str = yourdt.strftime("%Y-%m-%d %H:%M:%S")
that's it
from datetime import datetime
now = datetime.now() # current date and time
year = now.strftime("%Y")
print("year:", year)
month = now.strftime("%m")
print("month:", month)
day = now.strftime("%d")
print("day:", day)
time = now.strftime("%H:%M:%S")
print("time:", time)
date_time = now.strftime("%m/%d/%Y, %H:%M:%S")
print("date and time:",date_time)

Python: How to calculate time duration between current time and a specific time? [duplicate]

I have two datetime.time values, exit and enter and I want to do something like:
duration = exit - enter
However, I get this error:
TypeError: unsupported operand type(s) for -: 'datetime.time' and
'datetime.time
How do I do this correctly? One possible solution is converting the time variables to datetime variables and then subtruct, but I'm sure you guys must have a better and cleaner way.
Try this:
from datetime import datetime, date
datetime.combine(date.today(), exit) - datetime.combine(date.today(), enter)
combine builds a datetime, that can be subtracted.
Use:
from datetime import datetime, date
duration = datetime.combine(date.min, end) - datetime.combine(date.min, beginning)
Using date.min is a bit more concise and works even at midnight.
This might not be the case with date.today() that might return unexpected results if the first call happens at 23:59:59 and the next one at 00:00:00.
instead of using time try timedelta:
from datetime import timedelta
t1 = timedelta(hours=7, minutes=36)
t2 = timedelta(hours=11, minutes=32)
t3 = timedelta(hours=13, minutes=7)
t4 = timedelta(hours=21, minutes=0)
arrival = t2 - t1
lunch = (t3 - t2 - timedelta(hours=1))
departure = t4 - t3
print(arrival, lunch, departure)
You have two datetime.time objects so for that you just create two timedelta using datetime.timedetla and then substract as you do right now using "-" operand. Following is the example way to substract two times without using datetime.
enter = datetime.time(hour=1) # Example enter time
exit = datetime.time(hour=2) # Example start time
enter_delta = datetime.timedelta(hours=enter.hour, minutes=enter.minute, seconds=enter.second)
exit_delta = datetime.timedelta(hours=exit.hour, minutes=exit.minute, seconds=exit.second)
difference_delta = exit_delta - enter_delta
difference_delta is your difference which you can use for your reasons.
The python timedelta library should do what you need. A timedelta is returned when you subtract two datetime instances.
import datetime
dt_started = datetime.datetime.utcnow()
# do some stuff
dt_ended = datetime.datetime.utcnow()
print((dt_ended - dt_started).total_seconds())
datetime.time can not do it - But you could use datetime.datetime.now()
start = datetime.datetime.now()
sleep(10)
end = datetime.datetime.now()
duration = end - start
datetime.time does not support this, because it's nigh meaningless to subtract times in this manner. Use a full datetime.datetime if you want to do this.
import datetime
def diff_times_in_seconds(t1, t2):
# caveat emptor - assumes t1 & t2 are python times, on the same day and t2 is after t1
h1, m1, s1 = t1.hour, t1.minute, t1.second
h2, m2, s2 = t2.hour, t2.minute, t2.second
t1_secs = s1 + 60 * (m1 + 60*h1)
t2_secs = s2 + 60 * (m2 + 60*h2)
return( t2_secs - t1_secs)
# using it
diff_times_in_seconds( datetime.datetime.strptime( "13:23:34", '%H:%M:%S').time(),datetime.datetime.strptime( "14:02:39", '%H:%M:%S').time())
timedelta accepts negative(-) time values. so it could be simple as below.
Answer (single line)
datetime.timedelta(hours=exit.hour-enter.hour, minutes=exit.minute-enter.minute)
Run test
import datetime
enter = datetime.time(hour=1, minute=30)
exit = datetime.time(hour=2, minute=0)
duration = datetime.timedelta(hours=exit.hour-enter.hour, minutes=exit.minute-enter.minute)
>>> duration
datetime.timedelta(seconds=1800)
I had similar situation as you and I ended up with using external library called arrow.
Here is what it looks like:
>>> import arrow
>>> enter = arrow.get('12:30:45', 'HH:mm:ss')
>>> exit = arrow.now()
>>> duration = exit - enter
>>> duration
datetime.timedelta(736225, 14377, 757451)
import time
from datetime import datetime
def calcTime(enter,exit):
format="%H:%M:%S"
#Parsing the time to str and taking only the hour,minute,second
#(without miliseconds)
enterStr = str(enter).split(".")[0]
exitStr = str(exit).split(".")[0]
#Creating enter and exit time objects from str in the format (H:M:S)
enterTime = datetime.strptime(enterStr, format)
exitTime = datetime.strptime(exitStr, format)
return exitTime - enterTime
enter = datetime.today().time()
#Sleeping for 5 seconds before initializing the exit variable
time.sleep(5)
exit = datetime.today().time()
duration = calcTime(enter,exit)
print(f"Duration is {duration} (Hours:Minutes:Seconds)")
#Output: Duration is 0:00:05 (Hours:Minutes:Seconds)
If it is helpful, you can use the calcTime function as shown.

Getting and formatting today and yesterdays date

I have seen this question asked and answered alot, but for some reason I am having trouble.
I am just trying to print out todays date and yesterdays date as mm-dd-yyyy.
This works without error:
from datetime import date, timedelta
today = date.today()
yesterday = today - timedelta(days = 1)
print(today)
print(yesterday)
Output:
2019-08-21
2019-08-20
However, if I try to format it with this, I get an error:
from datetime import date, timedelta
today = date.today()
yesterday = today - timedelta(days = 1)
yesterday.strftime('%m-%d-%Y')
today.strftime('%m-%d-%Y')
print(today)
print(yesterday)
Error:
.strftime('%m-%d-%Y')
^ SyntaxError: invalid syntax
Thanks in advance for any help
To print out in the format mm-dd-yyyy you just have to do the following:
In [1]: from datetime import date, timedelta,datetime
...: today = date.today()
...: yesterday = today - timedelta(days = 1)
In [2]: print(datetime.strftime(today,'%m-%d-%Y'))
...: print(datetime.strftime(yesterday,'%m-%d-%Y'))
08-21-2019
08-20-2019
You need to return an strftime function.
from datetime import date, timedelta
time = date.today();
time2 = data.today();
time = time.strftime('%m-%d-%Y');
print(time);
// or
print( time2.strftime('%m-%d-%Y') );
Both outputs are:
>>'08-21-2019'
>>'08-21-2019'
You can look up more on each function by typing help(funct) in console or IDE, where funct is function name or syntax to look up. And you can look up all methods for classes and objects by typing help(obj). By typing dir(obj) you can have all methods/functions as an list.
A quick check if function returns a value is to just print it out. If function doesn't return value the print function will display None into the console, signifying that it didn't get anything from the function.

How to combine dates and times?

I want to add a time to a datetime. My initial datetime is: initial_datetime='2015-11-03 08:05:22' and is a string and this_hour and this_min are strings too. I use:
time='-7:00'
time = time.split(':')
this_hour = time[0]
this_min = time[1]
initial_datetime='2015-11-03 08:05:22'
new_date = datetime.combine(initial_datetime, time(this_hour, this_min))
+ timedelta(hours=4)
But there comes an error:
'str' object is not callable.
My desired output is the initial_datetime plus my time (in this case -7 hours ) and then add 4 hours. So, in my example, the new date should be '2015-11-03 05:05:22'.
datetime.combine is typically used to combine a date object with a time object rather than incrementing or decrementing a datetime object. In your case, you need to convert your datetime string to a datetime object and convert the parts of your time string to integers so you can add them to your datetime with timedelta. As an aside, be careful about using variable names, like time, that conflict with your imports.
from datetime import datetime, timedelta
dtstr = '2015-11-03 08:05:22'
tstr = '-7:00'
hours, minutes = [int(t) for t in tstr.split(':')]
dt = datetime.strptime(dtstr, '%Y-%m-%d %H:%M:%S') + timedelta(hours=hours+4, minutes=minutes)
print(dt)
# 2015-11-03 05:05:22

Python: format datetime efficiently whilst leaving it as a datetime object

I want to be able to format a datetime object, while leaving it as an object. I have worked a way to do it, but it doesn't seem very efficient.
My specific aim is to limit the extra digits on the seconds to 2. This is how I am currently doing it:
now = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
now_frmt = datetime.datetime.strptime(now, '%Y-%m-%d %H:%M:%S')
Cheers,
JJ
You could do this to subtract off the microseconds:
now = datetime.datetime.now()
now_frmt = now - datetime.timedelta(microseconds=now.microsecond)
To round to the nearest second you can do the following:
now = datetime.datetime.now()
delta = (0 if now.microsecond < 500000 else 1000000) - now.microsecond
now_frmt = now + datetime.timedelta(microseconds=delta)

Categories

Resources