I would like to execute a portion of script once daily for about 7 days. I used the datetime module in getting the current date, the timedelta module in calculating the runtime of the program, and the localtime() in specifying a particular time the code is to run daily. The first time I executed it, the balance doesn't add up automically. I think it keeps reassigning the balance variable.
Here is a portion of my code.
balance = 0
percentage = 5
deposit = 0
profit = 0
active = True
while active:
if current_date < expiring_date:
balance = deposit + percentage
current_date = current_date + timedelta(hours=24)
if time.localtime().tm_hr == 2:
balance += percentage
else:
active = False
Then, I modified the code by using conditionals to check if the initial balance is 0, to prevent the reassign ing. Currently the code executes at once, which is not what I want. I want it to run daily, and for each run, it should add the percentage to the current balance till the codition evaluates to False. I also want to keep a track of balance, and return the new balance at the end of each day. Is there a better way of doing it without keeping the loop running for days,and consuming power.
while active:
if current_date < expiring_date:
if balance <= 0:
balance = deposit + percentage
current_date = current_date + timedelta(hours=24)
else:
if time.localtime().tm_hr == 2:
balance += percentage
current_date = current_date + timedelta(hours=24)
else:
active = False
Related
# making a basic calendar
#list of months and their days
month_day = [[1,'January',31],[2,'February',28],
[3,'March',31],[4,'April',30],
[5,'May',31],[6,'June',30],
[7,'July',31],[8,'August',31],
[9,'September',30],[10,'October',31],
[11,'November',30],[12,'December',31]]
#checksum for new year
def isleapyear(year):
if year%4 == 0:
if year%100 == 0:
if year%400 == 0:
month_day[1][2] = 29
else:
month_day[1][2] = 28
else :
month_day[1][2] = 29
else:
month_day[1][2] = 28
#editable date (supposed to be
def Date():
year = 1
day = 31
month = 1
isleapyear(year)
date = [day, month_day[month-1][1], year]
return date
#function to increase day counter by 1
def new_day():
#checksum for month or year rollover
if Date.day == month_day[Date.month-1][2]:
Date.day = 1
if Date.month == 12:
Date.month = 1
Date.year = Date.year + 1
else:
Date.month = month + 1
else:
Date.day = Date.day + 1
new_day()
print (Date())
I am trying to teach myself python, so I have made a project a few smaller projects working together and one of them is a Date tracker. The Date function works. however when i try to call the new day function to bump the day by 1 and change month and year if needed, i get an error "AttributeError: 'function' object has no attribute 'day'". I understand that inside a function is a separate local variable not a global and that your not supposed to make global variables constantly changing. So I'm trying to get one function to call and use anothers variable I plan on making it into a button that changes the day by 1 or 7, I'm just having trouble visualizing how to get the function working. Any direction or help with getting this to work would be greatly appreciated
Thank you all in advance!
Firstly, you can't get variables from function.
One way you can deal with it is in function Date add line global year, day, month, this will make variables year, day, month global so you can use it in all function and outside of functions. And in new_day remove Date..
This should get rid of your problem.
Date.day would only work if Date was class not function.
For example:
class Date:
def __init__(self):
self.year = 1
self.day = 31
self.month = 1
Date().year # Should return 1
Date().day # Should return 31
Date().month # Should return 1
I want to schedule a celery task at random possible days and also on last day of every month. Is it possible to store the schedule of a celery task in certain way that the task gets picked up both in middle of the month and the last day of month as well. Last day of month of course is not static. Is it possible to store two different cron expressions for single task. I tried a cron expression with L for last month as suggested in many sites. but it doesn't seem to be a standard.
I don't think it's supported out of the box, but it looks fairly doable to write a custom schedule. Celery supports crontab and solar schedules, and they are Python classes so I assume one could create its own.
I haven't tested it, but it looks like it should be something along the lines of:
import calendar
import datetime
from celery.schedules import BaseSchedule, schedstate
class last_day_month(BaseSchedule):
def is_due(self, last_run_at):
"""Return tuple of ``(is_due, next_time_to_run)``.
Note:
next time to run is in seconds.
See Also:
:meth:`celery.schedules.schedule.is_due` for more information.
"""
# Same as the one from crontab schedule class
rem_delta = self.remaining_estimate(last_run_at)
rem = max(rem_delta.total_seconds(), 0)
due = rem == 0
if due:
rem_delta = self.remaining_estimate(self.now())
rem = max(rem_delta.total_seconds(), 0)
return schedstate(due, rem)
def remaining_estimate(self, last_run_at):
"""Estimate of next run time.
Returns when the periodic task should run next as a
:class:`~datetime.timedelta`.
"""
last_run_at = self.maybe_make_aware(last_run_at)
now = self.maybe_make_aware(self.now())
if last_run_at.month == now.month:
# Already run this month: next time is next month
month = now.month + 1 if now.month < 12 else 1
year = now.year + 1 if now.month < 12 else 1
else:
# Otherwise, should run this month next
month, year = now.month, now.year
# We've got the month and year, now get the last day
_first_day, last_day = calendar.monthrange(year, month)
# Build the datetime for next run
next_utc = self.maybe_make_aware(
datetime.datetime(year=year, month=month, day=last_day)
)
# Return the timedelta from now
return next_utc - now
This is to be used in place of the crontab class in your Celery schedule
I have been studying Python by myself since a month ago.
I want to make a duration calculator that shows the total time of each different duration.
For instance, there are two different flights I have to take, and I want to get the total time I would be in the airplanes. It goes like this.
a = input('Enter the duration: ') #11h40m
b = input('Enter the duration: ') #13h54m
#it may show the total duration
01d01h34m
Try this :
Edit : I tried to use strftime to format the 'duration' but had some issues with day.
So I did it manually (you can format it the way you wish)
import datetime
import time
# Convert str to strptime
a_time = datetime.datetime.strptime("11h40m", "%Hh%Mm")
b_time = datetime.datetime.strptime("13h54m", "%Hh%Mm")
# Convert to timedelta
a_delta = datetime.timedelta(hours = a_time.hour,minutes=a_time.minute)
b_delta = datetime.timedelta(hours = b_time.hour,minutes=b_time.minute)
duration = (a_delta + b_delta)
print(str(duration.days) + time.strftime('d%Hh%Mm', time.gmtime(duration.seconds)))
'1d01h34m'
I would like to format the output in terms of calendar format. I have tried with print statement, but could not achieve as I expected because rows and column is not aligned properly.Could anyone help me to format and align the output? Here I have shared my entire code which is written in Python 3.6. the same question I have asked before but could not get any reply. but this code is little better than my previous code.
import calendar
import datetime
tamil_day = ('Monday','Tuesday','Wednesday','Thusday','Friday','Saturday','Sunday')
tamil_month = ('Chithirai','Vaikasi','Aani','Aadi','Aavani','Puratasi','Ipasi','Karthikai','Maargali','Thai','Masi','Panguni')
'''SAKA year Each month starting day in AD year 1st position for common year and 0th position for leap year'''
saka_month_starting_day_in_ad = (21,22,21,22,22,23,23,23,23,22,22,21,20)
'''equal month in AD year for SAKA month starting'''
ad_month = (3,3,4,5,6,7,8,9,10,11,12,1,2)
''' number of days in each month in SAKA year. add one ine more day each month for calculation'''
no_days_in_saka_month = (31,30,31,31,31,31,31,30,30,30,30,30,30)
def saka_month(saka_year,month):
ad_year = saka_year+78
saka_month = []
temp = 0
if month == 1 and calendar.isleap(ad_year):
first_day = datetime.date(ad_year,ad_month[month],saka_month_starting_day_in_ad[month-1]).weekday()
else:
first_day = datetime.date(ad_year,ad_month[month],saka_month_starting_day_in_ad[month]).weekday()
while first_day != temp:
saka_month.append(str(' '))
temp+=1
for day in range(1,(no_days_in_saka_month[month]+1)):
saka_month.append(str(day))
if day == no_days_in_saka_month[month] and calendar.isleap(ad_year):
saka_month.append(str(day+1))
for i in range(0,42,7):
print(*saka_month[i:i+7],sep=' ',end='\n')
print('\n')
def saka_year_print(saka_year):
for month in range(0,12):
print('{:*^80}'.format(tamil_month[month]))
print('\n')
print(*tamil_day,sep=' ')
print('\n','\n','\n')
saka_month(saka_year,month)
i have found the solution to my problem. just add str.center() for every list element. in my code at line no.47,50 and 52 you can add the center() function so that we can get aligned matrix kind of calendar in month view.
thank you
I want to make an app that when run, it will get the current date and time from the user's computer, and then count down to a week later at the time of running.
So for example:
The user runs the app on 06-06-2017 11:00:00, it must do a count down to a deadline a week later and display the deadline date and time, and show a count down of how many days, hours, minutes and seconds are left.
EDIT:
So far I have only been able to get the date and time and the time increments normally per second. I am having difficulty decrementing it. Without the last line of the code the time decrements but does not update automatically. I have yet to find a way to perform a count down from a week in advance.
def updateTime():
X = 1
t = datetime.datetime.now()
s = t.replace(microsecond=0)
result = s - datetime.timedelta(seconds=X)
future = s + datetime.timedelta(days=7, hours=0, minutes=0, seconds=0)
lblTime.configure(text=result, font=("", 14))
lblTime.after(100, updateTime)
You definitely want to calculate the target time only once instead of getting it every time the updateTime handler runs. Furthermore, you can simply do arithmetic on datetime objects to get a timedelta object back which you can then display in your GUI.
Here is an example that is printing the output to the console. You can probably adjust this as needed to make it display in your GUI.
import datetime
target_time = datetime.datetime.now() + datetime.timedelta(days=7)
target_time = target_time.replace(microsecond=0)
def get_remaining_time():
delta = target_time - datetime.datetime.now()
hours = delta.seconds // 3600
minutes = (delta.seconds % 3600) // 60
seconds = delta.seconds % 60
print('{} days, {} hours, {} minutes, {} seconds'.format(delta.days, hours, minutes, seconds))
while True:
get_remaining_time()