I need to write my program output to a log file whose name should change every 15 minutes and
currently I am doing this way.
import time
from datetime import datetime
FullLog = datetime.today().strftime("Prog1TempLog1_%d_%m_%Y") + ".txt"
today0915 = datetime.now().replace(hour=9, minute=15, second=0,microsecond=0)
today0930 = datetime.now().replace(hour=9, minute=30, second=0,microsecond=0)
today0945 = datetime.now().replace(hour=9, minute=45, second=0,microsecond=0)
today1000 = datetime.now().replace(hour=10, minute=0, second=0,microsecond=0)
today1015 = datetime.now().replace(hour=10, minute=15, second=0,microsecond=0)
while <my condition>:
if datetime.now() > today0915 and datetime.now() <= today0930:
FullLog = datetime.today().strftime("Prog1Log1_%d_%m_%Y") + ".txt"
if datetime.now() > today0930 and datetime.now() <= today0945:
FullLog = datetime.today().strftime("Prog1Log2_%d_%m_%Y") + ".txt"
if datetime.now() > today0945 and datetime.now() <= today1000:
FullLog = datetime.today().strftime("Prog1Log3_%d_%m_%Y") + ".txt"
if datetime.now() > today0945 and datetime.now() <= today1000:
FullLog = datetime.today().strftime("Prog1Log4_%d_%m_%Y") + ".txt"
if datetime.now() > today1000 and datetime.now() <= today1015:
FullLog = datetime.today().strftime("Prog1Log5_%d_%m_%Y") + ".txt"
print("Time", datetime.now(), "FileName:", FullLog)
time.sleep(1)
Is there any dynamic way to do this procedure.
During while loop, get the current time. Then figure out how many minutes does it have. For ex., 10:20 has 20 minutes. Now divide it by 15 and add 1 to get the file name.
now = datetime.today().minute
log_seq = num//15 + 1 #just check edge cases around 60 and 00 .. // for python3
FullLog = datetime.today().strftime("Prog1Log"+log_seq+"_%d_%m_%Y") + ".txt"
Related
I would like to write a function that calculate working business hours in python, to do that I don't like to define a class and use python ready function to calculate.
I tried with following code but the code is not working well. I need to modify the code and change it for the hour instead of minutes too.
Do you have any suggestion?
def getminutes(datetime1,datetime2,worktiming=[9, 17]):
day_hours = (worktiming[1]-worktiming[0])
day_minutes = day_hours * 60 # minutes in a work day
weekends=[6, 7]
# Set initial default variables
dt_start = datetime1.datetime # datetime of start
dt_end = datetime2.datetime # datetime of end
worktime_in_seconds = 0
if dt_start.date() == dt_end.date():
# starts and ends on same workday
full_days = 0
if dt_start in [6, 7]:
return 0
else:
if dt_start.hour < worktiming[0]:
# set start time to opening hour
dt_start = datetime.datetime(
year=dt_start.year,
month=dt_start.month,
day=dt_start.day,
hour=worktiming[0],
minute=0)
if dt_start.hour >= worktiming[1] or \
dt_end.hour < worktiming[0]:
return 0
if dt_end.hour >= worktiming[1]:
dt_end = datetime.datetime(
year=dt_end.year,
month=dt_end.month,
day=dt_end.day,
hour=worktiming[1],
minute=0)
worktime_in_seconds = (dt_end-dt_start).total_seconds()
elif (dt_end-dt_start).days < 0:
# ends before start
return 0
else:
# start and ends on different days
current_day = dt_start # marker for counting workdays
while not current_day.date() == dt_end.date():
if not is_weekend(current_day):
if current_day == dt_start:
# increment hours of first day
if current_day.hour < worktiming[0]:
# starts before the work day
worktime_in_seconds += day_minutes*60 # add 1 full work day
elif current_day.hour >= worktiming[1]:
pass # no time on first day
else:
# starts during the working day
dt_currentday_close = datetime.datetime(
year=dt_start.year,
month=dt_start.month,
day=dt_start.day,
hour= worktiming[1],
minute=0)
worktime_in_seconds += (dt_currentday_close
- dt_start).total_seconds()
else:
# increment one full day
worktime_in_seconds += day_minutes*60
current_day += datetime.timedelta(days=1) # next day
# Time on the last day
if not is_weekend(dt_end):
if dt_end.hour >= worktiming[1]: # finish after close
# Add a full day
worktime_in_seconds += day_minutes*60
elif dt_end.hour < worktiming[0]: # close before opening
pass # no time added
else:
# Add time since opening
dt_end_open = datetime.datetime(
year=dt_end.year,
month=dt_end.month,
day=dt_end.day,
hour=worktiming[0],
minute=0)
worktime_in_seconds += (dt_end-dt_end_open).total_seconds()
return int(worktime_in_seconds / 60)
How can I modify the code that works with the following input ?
getminutes(2019-12-02 09:30:00,2019-12-07 12:15:00,worktiming=[9, 17])
You can use pd.bdate_range(datetime1, datetime2) to compute the number of working days. When converting worktiming to a pandas datetime, it is easy to compute the difference (in seconds) between the two datetimes:
import pandas as pd
datetime1 = "2019-12-02 09:30:00"
datetime2 = "2019-12-07 12:15:00"
def getminutes(datetime1, datetime2, worktiming=[9, 17]):
d1 = pd.to_datetime(datetime1)
d2 = pd.to_datetime(datetime2)
wd = pd.bdate_range(d1, d2) # working days
day_hours = (worktiming[1] - worktiming[0])
day_minutes = day_hours * 60 # minutes in a work day
day_seconds = day_minutes * 60 # seconds in a work day
full_days = len(wd)
day1 = datetime1[:10]
day2 = datetime2[:10]
dt1 = pd.to_datetime(day1 + " " + str(worktiming[0]) + ":00")
dt2 = pd.to_datetime(day2 + " " + str(worktiming[1]) + ":00")
ex1, ex2 = 0, 0
if day1 in wd:
ex1 = max(pd.Timedelta(d1 - dt1).seconds, 0)
if day2 in wd:
ex2 = max(pd.Timedelta(dt2 - d2).seconds, 0)
total_seconds = full_days * day_seconds - ex1 - ex2
total_minutes = total_seconds / 60
total_hours = total_minutes / 60
return int(total_minutes)
print(getminutes(datetime1, datetime2))
Output: 2370
If I was able to execute a function a (user-specified) amount of time between two dates, how would I do it?
Am I on the right track?
from datetime import date, datetime
from upload import *
current_time = datetime.utcnow()
start_time = datetime.time.hour(17)
end_time = datetime.time.hour(20)
imageposts = []
post_limit = 0
for imagepost in imageposts:
if start_time <= current_time & current.time <= end_time & post_limit <= 3:
try:
upload()
postlimit += 1
except:
print('Current time is not between times')
Try this:
from datetime import datetime
from upload import *
current_time = datetime.utcnow()
year, month, day = current_time.year, current_time.month, current_time.day
start_time = datetime(year, month, day, 17)
end_time = datetime(year, month, day, 20, 59, 59)
imageposts = []
post_limit = 0
for imagepost in imageposts:
if start_time <= current.time <= end_time and post_limit <= 3:
try:
upload()
post_limit += 1
except:
print('Current time is not between times')
I'm working on my python script to get the strings from the button objects so I can use it to set the date formats with the time that I got from the strings to store it in the lists. When I get the strings from the button objects, I want to set the date for each string, example: 29/08/2017 11:30PM, 30/08/2017 12:00AM, 30/08/2017 12:30AM.
When I try this:
if day_date >= 0 and day_date <= 6:
if epg_time3 == '12:00AM':
if day_date > 0:
currentday = datetime.datetime.now() + datetime.timedelta(days = 0)
nextday = datetime.datetime.now() + datetime.timedelta(days = self.program_day)
if currentday != nextday:
epg_time_1 = datetime.datetime.now() + datetime.timedelta(days = self.program_day + 1)
epg_time_2 = datetime.datetime.now() + datetime.timedelta(days = self.program_day + 1)
epg_time_3 = datetime.datetime.now() + datetime.timedelta(days = self.program_day + 1)
elif currentday == nextday:
epg_time_1 = datetime.datetime.now() + datetime.timedelta(days = self.program_day)
epg_time_2 = datetime.datetime.now() + datetime.timedelta(days = self.program_day - 1)
epg_time_3 = datetime.datetime.now() + datetime.timedelta(days = self.program_day - 1)
It will show the output:
self.epg_time_1
['29/08/2017 11:00PM']
self.epg_time_2
['29/08/2017 11:30PM']
self.epg_time_3
['29/08/2017 12:00AM']
When I'm calling the EPG_Times function again, it will show the output like this:
self.epg_time_1
['30/08/2017 11:00PM']
self.epg_time_2
['30/08/2017 11:30PM']
self.epg_time_3
['30/08/2017 12:00AM']
It should be:
self.epg_time_1
['30/08/2017 11:00PM']
self.epg_time_2
['30/08/2017 11:30PM']
self.epg_time_3
['31/08/2017 12:00AM']
As you can see the time 12:00AM is the next day so I want to set it to 31 not 30. I have changed from days = self.program_day + 1 to days = self.program_day - 1, but when the strings show 11:00PM, 11:30PM and 12:00AM from the variables epg_time_1, epg_time_2 and epg_time_3, it will show the output like this:
self.epg_time_1
['30/08/2017 11:00PM']
self.epg_time_2
['30/08/2017 11:30PM']
self.epg_time_3
['30/08/2017 12:00AM']
Here is the full code:
self.program_day = list()
def EPG_Times(self):
self.epg_time_1 = list()
self.epg_time_2 = list()
self.epg_time_3 = list()
epg_time1 = str(self.getControl(344).getLabel())
epg_time2 = str(self.getControl(345).getLabel())
epg_time3 = str(self.getControl(346).getLabel())
day_date = self.program_day
day = ''
month = ''
year = ''
if day_date >= 0 and day_date <= 6:
if epg_time3 == '12:00AM':
if day_date == 0:
if epg_time1 == '12:00AM':
epg_time_1 = datetime.datetime.now() + datetime.timedelta(days = self.program_day + 1)
epg_time_2 = datetime.datetime.now() + datetime.timedelta(days = self.program_day + 1)
epg_time_3 = datetime.datetime.now() + datetime.timedelta(days = self.program_day + 1)
else:
epg_time_1 = datetime.datetime.now() + datetime.timedelta(days = self.program_day)
epg_time_2 = datetime.datetime.now() + datetime.timedelta(days = self.program_day)
epg_time_3 = datetime.datetime.now() + datetime.timedelta(days = self.program_day + 1)
else:
currentday = datetime.datetime.now() + datetime.timedelta(days = 0)
nextday = datetime.datetime.now() + datetime.timedelta(days = self.program_day)
if currentday != nextday:
epg_time_1 = datetime.datetime.now() + datetime.timedelta(days = self.program_day + 1)
epg_time_2 = datetime.datetime.now() + datetime.timedelta(days = self.program_day + 1)
epg_time_3 = datetime.datetime.now() + datetime.timedelta(days = self.program_day + 1)
elif currentday == nextday:
epg_time_1 = datetime.datetime.now() + datetime.timedelta(days = self.program_day)
epg_time_2 = datetime.datetime.now() + datetime.timedelta(days = self.program_day - 1)
epg_time_3 = datetime.datetime.now() + datetime.timedelta(days = self.program_day - 1)
epg1_day = epg_time_1.strftime("%d")
epg1_month = epg_time_1.strftime("%m")
epg1_year = epg_time_1.strftime("%Y")
epg2_day = epg_time_2.strftime("%d")
epg2_month = epg_time_2.strftime("%m")
epg2_year = epg_time_2.strftime("%Y")
epg3_day = epg_time_2.strftime("%d")
epg3_month = epg_time_2.strftime("%m")
epg3_year = epg_time_2.strftime("%Y")
half_hour = str(epg1_day + "/" + epg1_month + "/" + epg1_year + " " + epg_time1)
one_hour = str(epg2_day + "/" + epg2_month + "/" + epg2_year + " " + epg_time2)
one_hour_half = str(epg3_day + "/" + epg3_month + "/" + epg3_year + " " + epg_time3)
#Store the times and date in the list....
self.epg_time_1.append(half_hour)
self.epg_time_2.append(one_hour)
self.epg_time_3.append(one_hour_half)
What I'm expected the code to do is to change to the previous day date for each string that I get from the button objects when I call the EPG_time(self) function. If the epg_time_1 and epg_time_2 show the strings 11:00PM and 11:30PM, I want to set the time and date to 29/08/2017 11:00PM for epg_time_1 and 29/08/2017 11:30PM for the epg_time_2. If the epg_time_3 show the string 12:00AM then I want to add it to the next day date with the time 30/08/2017 12:00AM.
In the next 24 hours if the epg_time_1 and epg_time_2 show the strings 11:00PM and 11:30PM, I want to set the time and date to 30/08/2017 11:00PM for epg_time_1 and 30/08/2017 11:30PM for the epg_time_2. If the epg_time_3 show the string 12:00AM then I want to set to the next day date with the time 1/09/2017 12:00AM
If the epg_time_1 and epg_time_2 show the strings 11:30PM and 12:00AM, I want to change to the previous date for epg_time_1 which it is 29/08/2017 11:30PM and 30/08/2017 12:00AM. It will be depends on the time and date when I have stored the strings in the list.
Can you please tell me an example how I could use to change the date to the previous date and add to the next day date using in python?
There's a lot of text in your question that makes it hard to pinpoint the issue exactly. However, it appears to boil down to adding a variable number of days to a particular date and ensuring that the month is also updated (if necessary).
You should use the datetime.datetime.strptime() method to convert your dates to datetimes, which makes it trivial to add timedelta (you use both timedelta and strftime but miss this crucial method) and then just convert back to a string.
import datetime as dt
def add_days(datelist, days_to_add):
# Convert the strings to datetime objects
datelist = [dt.datetime.strptime(item, '%d/%m/%Y %I:%M%p')
for item in datelist]
# Add a variable number of days (can be negative) to the datetimes
mod_dates = [item + dt.timedelta(days=days_to_add) for item in datelist]
# Convert back to strings
str_dates = [dt.datetime.strftime(item, '%d/%m/%Y %I:%M%p')
for item in mod_dates]
return str_dates
# This is the list right at the top of your question
a = ['29/08/2017 11:30PM', '30/08/2017 12:00AM', '30/08/2017 12:30AM']
print("Start:")
print(a)
b = add_days(a, 1)
print("After 1 call:")
print(b)
c = add_days(b, 1)
print("After 2 calls:")
print(c)
I have time string 11:15am or 11:15pm.
I am trying to convert this string into UTC timezone with 24 hour format.
FROM EST to UTC
For example: When I pass 11:15am It should convert into 15:15 and when I pass 11:15pm then it should convert to 3:15.
I have this code which I am trying:
def appointment_time_string(time_str):
import datetime
a = time_str.split()[0]
# b = re.findall(r"[^\W\d_]+|\d+",a)
# c = str(int(b[0]) + 4) + ":" + b[1]
# print("c", c)
in_time = datetime.datetime.strptime(a,'%I:%M%p')
print("In Time", in_time)
start_time = str(datetime.datetime.strftime(in_time, "%H:%M:%S"))
print("Start TIme", start_time)
if time_str.split()[3] == 'Today,':
start_date = datetime.datetime.utcnow().strftime("%Y-%m-%dT")
elif time_str.split()[3] == 'Tomorrow,':
today = datetime.date.today( )
start_date = (today + datetime.timedelta(days=1)).strftime("%Y-%m-%dT")
appointment_time = str(start_date) + str(start_time)
return appointment_time
x = appointment_time_string(time_str)
print("x", x)
But this is just converting to 24 hour not to UTC.
To convert the time from 12 hours to 24 hours format, you may use below code:
from datetime import datetime
new_time = datetime.strptime('11:15pm', '%I:%M%p').strftime("%H:%M")
# new_time: '23:15'
In order to convert time from EST to UTC, the most reliable way is to use third party library pytz. Refer How to convert EST/EDT to GMT? for more details
Developed the following script using provided options/solutions to satisfy my requirement.
def appointment_time_string(time_str):
import datetime
import pytz
a = time_str.split()[0]
in_time = datetime.datetime.strptime(a,'%I:%M%p')
start_time = str(datetime.datetime.strftime(in_time, "%H:%M:%S"))
if time_str.split()[3] == 'Today,':
start_date = datetime.datetime.utcnow().strftime("%Y-%m-%d")
elif time_str.split()[3] == 'Tomorrow,':
today = datetime.date.today( )
start_date = (today + datetime.timedelta(days=1)).strftime("%Y-%m-%d")
appointment_time = str(start_date) + " " + str(start_time)
# print("Provided Time", appointment_time)
utc=pytz.utc
eastern=pytz.timezone('US/Eastern')
fmt='%Y-%m-%dT%H:%M:%SZ'
# testeddate = '2016-09-14 22:30:00'
test_date = appointment_time
dt_obj = datetime.datetime.strptime(test_date,'%Y-%m-%d %H:%M:%S')
dt_str = datetime.datetime.strftime(dt_obj, '%m/%d/%Y %H:%M:%S')
date=datetime.datetime.strptime(dt_str,"%m/%d/%Y %H:%M:%S")
date_eastern=eastern.localize(date,is_dst=None)
date_utc=date_eastern.astimezone(utc)
# print("Required Time", date_utc.strftime(fmt))
return date_utc.strftime(fmt)
I want to write a program that allows the user to enter in a start time hour, end time hour, and number of divisions.
So they might enter 9, 10, and 4 which should mean a start time of 9:00AM, end of 10:00AM and to split the range 4 times, resulting in an output of 9:00, 9:15, 9:30, 9:45.
I've tried using the time module and datetime, but cannot get the addition of time to work. I do not care about date.
I can calculate the time split, but the actual addition to the start time is evading me.
I have a hodge-podge of code, and the following is mostly me experimenting trying to figure out how to make this work. I've tried adding the minutes, tried converting to seconds, delved into datetime, tried the time module, but can't seem to get it to work. There are plenty of examples of how to "add 15 minutes to now" but the issue is I don't want to start at the "now", but rather let the user decide start time.
Thank you.
time_start = "9"
time_end = "10"
time_split = "4"
if len(time_start) == 1:
time_start = "0" + str(time_start) + ":00"
else:
time_start = str(time_start) + ":00"
if len(time_end) == 1:
time_end = "0" + str(time_end) + ":00"
else:
time_end = str(time_end) + ":00"
print time_start
print time_end
s1 = time_start + ':00'
s2 = time_end + ':00'
FMT = '%H:%M:%S'
tdelta = datetime.strptime(s2, FMT) - datetime.strptime(s1, FMT)
divided = tdelta / int(time_split)
print tdelta
print divided
s3 = str(divided)
print "s1 time start: " + str(s1)
print "s2 time end: " + str(s2)
print "s3 time divided: " + str(s3)
ftr = [3600,60,1]
add_seconds = sum([a*b for a,b in zip(ftr, map(int,s3.split(':')))])
print "s3 time divided seconds: " + str(add_seconds)
print "time delta: " + str(tdelta)
EDIT: I did a small bit of research and found a much better solution that elegantly handles resolution to the millisecond. Please implement this code instead (though I will save the old code for posterity)
import datetime
start_time = 9 # per user input
end_time = 10 # per user input
divisions = 7 # per user input
total_time = end_time - start_time
start_time = datetime.datetime.combine(datetime.date.today(),datetime.time(start_time))
end_time = start_time + datetime.timedelta(hours=total_time)
increment = total_time*3600000//divisions # resolution in ms
times = [(start_time+datetime.timedelta(milliseconds=increment*i)).time()
for i in range(divisions)]
from pprint import pprint
pprint(list(map(str,times)))
# ['09:00:00',
# '09:08:34.285000',
# '09:17:08.570000',
# '09:25:42.855000',
# '09:34:17.140000',
# '09:42:51.425000',
# '09:51:25.710000']
If I were you, I'd do my math as raw minutes and use datetime.time only to save the results as something more portable.
Try this:
import datetime
start_time = 9 # per user input
end_time = 10 # per user input
divisions = 4 # per user input
total_minutes = (end_time-start_time)*60
increment = total_minutes // divisions
minutes = [start_time*60]
while minutes[-1] < end_time*60:
# < end_time*60 - increment to exclude end_time from result
minutes.append(minutes[-1] + increment)
times = [datetime.time(c//60,c%60) for c in minutes]
# [09:00:00,
# 09:15:00,
# 09:30:00,
# 09:45:00,
# 10:00:00]