How to add and subtract times in python [duplicate] - python

This question already has answers here:
How to compare times of the day?
(8 answers)
python time subtraction
(1 answer)
Closed 6 years ago.
I want to write a simple timesheet script. My input file looks like
9:00 17:00
10:45 12:35
11:00 15:00
I would like to read it in, compute the number of hours worked per day and then sum those hours up. When the day started before 12:00 and ended after 13:00 I would like to subtract half an hour too for lunch break.
My attempt so far is:
import sys
from datetime import datetime
gap = datetime.strptime('00:30','%H:%M')
hours = []
for line in sys.stdin:
(start_time,end_time) = line.split()
start_time = datetime.strptime(start_time, '%H:%M')
end_time = datetime.strptime(end_time, '%H:%M')
#if start_time before 12:00 and end_time after 13:00 then subtract gap
hours.append(end_time-start_time)
print sum(hours)
I don't know how to get the if statement line to work and summing the hours doesn't seem to work either as you can't sum datetime.timedelta types.
Thanks to the link in the comments, replacing sum(hours) with reduce(operator.add, hours) works.
The remaining part is how to test if start_time is before 12:00 and end_time is after 13:00 and if so to reduce the timedelta by half an hour.

You are using incorrect code (and syntax) in your if statement.
if start_time < datetime.strptime('12:00', '%H:%M') and end_time > datetime.strptime('13:00', '%H:%M'):
delta_hours = end_time.hour - start_time.hour)
delta_minutes = end_time.minutes - start_time.minutes)
# Do whatever your want with it now.
# Substraction of the break is not implemented in this example, it depends on how you want to save it.
Time delta might be worth looking into as well, it can use basic operations like
a = timedelta(...)
b = timedelta(...)
c = b - a - gap

Related

Python get date from days given

I need to calculate the date based on the number of minutes from the start of the year. I just need the day and month.
I have tried a few different classes within Python datetime but I can not get the desired result.
for example, at 1700 today, minutes since the 01/01/2022 is 263100
print(datetime.timedelta(0,0,0,0,263100))
This returns
182 days, 17:00:00
Before I explicitly write out the months and how many days they have and work it out that way, is there something already built in that I am missing within datetime?
I think this is what you are looking for. We add the minutes timedelta to the start datetime, and return it formatted.
from datetime import datetime, timedelta
def datesince_min(min:int, start:tuple=(2022,1,1)) -> str:
date = datetime(*start) + timedelta(minutes=min)
return date.strftime("%A, %B %d, %Y %I:%M:%S")
print(datesince_min(263100)) #Saturday, July 02, 2022 06:00:00
For more information regarding strftime formatting, refer to this.
Before I explicitly write out the months and how many days they have and work it out that way...
You shouldn't ever have to do that, and if you did it would almost certainly have to be for a system or language that is in development.
I found this code that should do the trick:
number_of_days = ((datetime.timedelta(0,0,0,0,263100)).split())[0]
months = (number_of_days - years * 365) // 30
days = (number_of_days - years * 365 - months*30)
print(months, days)
Where you replace 263100 with whatever minutes you wish ofc
(source: https://www.codesansar.com/python-programming-examples/convert-number-days-years-months-days.htm#:~:text=Python%20Source%20Code%3A%20Days%20to%20Years%2C%20Months%20%26,print%28%22Months%20%3D%20%22%2C%20months%29%20print%28%22Days%20%3D%20%22%2C%20days%29)
:)

How to compare two times [duplicate]

This question already has answers here:
How to compare times of the day?
(8 answers)
Closed 3 years ago.
I'm trying to compare two time in python:
from datetime import time, datetime
start = datetime(2020, 1 , 18, 9,30)
current_time = datetime.now()
if (current_time == start):
print("Time Matched")
Now when i'm running the code and when time reaches above mentioned start time, it does not prints "Time is matched" Kindly help me out in what im trying to do with this code is that when start time matches my laptop time i'm trying to execute some code , buy i'm not able to do so.
**Your PC Note down time with millisecond that's why you are not able to get desired result **
If You Provide second in datetime obj then -\
from datetime import time, datetime
start = datetime(2020, 1 , 18, 9,30)
current_time = datetime.now()
start_str=str(start)
current_str=str(surrent_time)
if(start_str==current_str):
print(match)
**General Method **
if we want to match particular part This is 23 hour format if you want 12 hour format you can find diff parameter answer
start = datetime(2020, 1 , 18, 9,30)
current = datetime.now()
start_year=start.strftime("%Y")
start_month=start.strftime("%m")
start_day=start.strftime("%H")
start_hours=start.strftime("%H")
start_min=start.strftime("%M")
print(start_year,start_month,start_day,start_hours,start_min)
current_year=current.strftime("%Y")
current_month=current.strftime("%m")
current_day=current.strftime("%H")
current_hours=current.strftime("%H")
current_min=current.strftime("%M")
print(current_year,current_month,current_day,current_hours,current_min)
if((start_year==current_year) and (start_month==current_month) and (start_day==current_day) and (start_hours==current_hours) and (start_min==current_min)):
print("match")

In Python, I want to subtract a time period from within a time period

I want to calculate hours of work during a day, and subtract lunchtime from that time. So somebody clocks in at 8:00, takes a lunch from 12:00 to 12:30, and finish at 16:00.
Lunchtime is configured in a settings table, with start-time and end-time.
So in a nutshell I want to calculate this:
endtime minus starttime = n hours:minutes of work, minus lunchtime (= 12:30 - 12:00 = 30 minutes)
How can I calculate this in Python without making this a hardcoded thing?
Help would be much appreciated
cheers
You can do it with Python datetime:
import datetime as dt
def work_time(start, end, lunch=[], format_='%H:%M'):
""" Calculate the hours worked in a day.
"""
start_dt = dt.datetime.strptime(start, format_)
end_dt = dt.datetime.strptime(end, format_)
if lunch:
lunch_start_dt = dt.datetime.strptime(lunch[0], format_)
lunch_end_dt = dt.datetime.strptime(lunch[1], format_)
lunch_duration = lunch_end_dt - lunch_start_dt
else:
lunch_duration = dt.timedelta(0)
elapsed = end_dt - start_dt - lunch_duration
hours = elapsed.seconds / 3600
return hours
>>> work_time('8:00', '16:00', lunch=['12:00', '12:30'])
7.5
The documentation for datetime provides more information on specific formatting and how to use timedeltas to perform operations on datetime and time objects.

Python - Split a time period into multiple time periods of fixed length

Given two dates, I would like to generate a list of dates with a fixed time length in between one another using datetime, starting from the later date.
For instance, given 01/01/2018 and 01/09/2018 and time interval of 2 months the output would be:
[01/01/2018, 01/03/2018, 01/05/2018, 01/07/2018, 01/09/2018]
For an interval of 3 months:
[01/03/2018, 01/06/2018, 01/09/2018]
I cannot just subtract months using the .replace method on a datetime object since going from a 31 days month to a 30 days month would return an error.
I think relativedeleta module can help you on this - pip install python-dateutil
from dateutil.relativedelta import *
import datetime
date1 = datetime.datetime.strptime('01/01/2018', "%d/%m/%Y").date()
date2 = datetime.datetime.strptime('01/09/2018', "%d/%m/%Y").date()
f = [(date1 + relativedelta(months=i)).strftime("%d/%m/%Y") for i in range(date1.month, date2.month,2)]
Result will be - ['01/02/2018', '01/04/2018', '01/06/2018', '01/08/2018']
You did specify datetime, but if you're interested,
a time.localtime object can be broken down like so:
import time
secSinceEpoch = time.time()
currentTime = time.localtime(secSinceEpoch)
month = currentTime.tm_mon
day = currentTime.tm_mday
year = currentTime.tm_year
hour = currentTime.tm_hour
min = currentTime.tm_min
sec = currentTime.tm_sec
From here you could perform operations on specific parts of the date/time...

Start and stop a Python script at a specific time

I am writing a script which will record the user activity in a certain period of time every day. The periods are taken from a JSON response of an API, like this:
[{"working_day": "mon", "work_start_at": "09:00", "work_end_at": "18:00"},
{"working_day": "tue", "work_start_at": "09:00", "work_end_at": "15:00"}]
Let's assume that I can parse these strings in a datetime() format.
I want to run my function accordingly to these periods and stop my function after "work_end_at". I found numerous example of how to run after certain amount of seconds, how to run every day (Python lib schedule) and examples with bash crontab. But nothing of this works for me, because all I want is to start the script at a specific time and stop at a specific time. And then, run again when the next "shift" comes.
def start():
time_periods = working_periods_table.find_all()
today = datetime.datetime.now().isoweekday()
for day in time_periods:
if day["day"] == today:
start_time = day["work_start_at"]
end_time = day["work_end_at"]
schedule.every().week.at(start_time).do(record_activity(idle_time=300))
If I've understood what you're asking, you could use while loops. Have it periodically check the current time with the times for the shift beginning and end. Below is a guide of what I mean, but I'm not sure the comparisons will work.
from time import sleep
def start():
time_periods = working_periods_table.find_all()
today = datetime.datetime.now().isoweekday()
for day in time_periods:
if day["day"] == today:
start_time = day["work_start_at"]
end_time = day["work_end_at"]
while True:
if datetime.datetime.now() >= start_time:
while True:
schedule.every().week.at(start_time).do(record_activity(idle_time=300))
if datetime.datetime.now() >= end_time:
break
break
else:
sleep(100)
I have some way to start my process at certain time but can not stop at certain time, I think you might means after running at 1 hour, even it is not finished yet, still stop the program. in this case you might can use while loop
take a look with my scripts first this might helpful
import time
from time import strftime, localtime
import datetime
now = datetime.datetime.now()
year = int(now.strftime("%Y"))
month = int(now.strftime("%m"))
day = int(now.strftime("%d"))
hour = int(now.strftime("%H"))
start_time_t = datetime.datetime(year=year, month=month, day=day, hour=22, minute=0, second=0)
waiting_time = time.mktime(start_time_t.timetuple()) - time.time()
if waiting_time >= 0:
print('the program will be start after ' + time.strftime("%H hours and %M minutes", time.gmtime(waiting_time)))
time.sleep(waiting_time)
else:
start_time_t = datetime.datetime(year=year, month=month, day=day + 1, hour=00, minute=0, second=0)
waiting_time = time.mktime(start_time_t.timetuple()) - time.time()
print('the program will be start after ' + time.strftime("%H hours and %M minutes", time.gmtime(waiting_time)))
time.sleep(waiting_time)
It will runs my program every day at 10:00 PM, if pass 10:00 PM the program will runs on the beginning of text day.
If you want to run your script at specific time intervals, I will suggest the code below which I have used on my own script. So simple to implement.
import datetime
now = datetime.datetime.now()
print(now.year, now.month, now.day, now.hour, now.minute, now.second)
# 2015 5 6 8 53 40
while True:
now = datetime.datetime.now()
if 14 <= now.hour and 23=> now.hour:
# put your code here
Note that in this piece of code I consider 2 PM until 11 PM. And more important you have to get the current hour persistently in a loop.
If you have a specific day in your mind get your current day out of the loop and compare it to your get value !! It works for me.

Categories

Resources