Python 3.xx : Classes in classes - python

I need help for my python scripts. How to access my clock's function through Date's classes ?
from datetime import date
from datetime import datetime
class Date(object):
def date_today(self):
now = date.today()
print (now)
class Time(Date):
pass
def clock(self):
hr = datetime.now()
hr_now = hr.hour
print (hr_now)
cr_date = Date()
print (cr_date.date_today())
print (cr_date.date_today.clock())
i got an error --> AttributeError: 'function' object has no attribute 'clock'. What is the reason for this error?

you can also add minute, second and other related functions in your time class. I hope it will help.
from datetime import date
from datetime import datetime
class Time():
def clock(self):
hr = datetime.now()
hr_now = hr.hour
return hr_now
class Date():
def __init__(self):
self.time = Time()
def date_today(self):
now = date.today()
return now
def clock(self):
return self.time.clock()
cr_date = Date()
print(cr_date.date_today())
print(cr_date.clock())

Related

Formatting todays date in python as date type

I'm trying to get todays date in the format %d/%m/%y without converting to a string. I still want to have the date as the data type.
Following code returns an str
today = date.today().strftime('%d/%m/%y')
print(type(today))
This is the right way to achieve your goal:
from datetime import date
today = date.today()
today_string = today.strftime('%d/%m/%Y')
print(type(today))
print(today_string)
Output:
<class 'datetime.date'>
26/10/2022
To change the date class default format:
mydatetime.py
from datetime import datetime as system_datetime, date as system_date
class date(system_date):
def __str__(self):. # similarly for __repr__
return "%02d-%02d-%02d" % (self._day, self._month, self._year)
class datetime(system_datetime):
def __str__(self):. # similarly for __repr__
return "%02d-%02d-%02d" % (self._day, self._month, self._year)
def date(self):
return date(self.year, self.month, self.day)
Read More: How to globally change the default date format in Python
The default datetime simply outputs as is; but you can inherit and create a custom __repr__:
from datetime import datetime
class mydatetime(datetime):
def __repr__(self):
return self.strftime('%d/%m/%y')
mydatetime.today()
outputs 26/10/22

timedelta issue in python3.9 vs.python3.6

I have the following class in a file called 'GPS_Date.py':
import datetime
from math import floor
class GPS_Date(datetime.datetime):
ref_date = datetime.datetime(1980, 1, 6)
def __init__(self, year, month, day, hour=0, minute=0, second=0):
datetime.datetime.__init__(year, month, day, hour, minute, second)
def gps_week(self):
difftime = self-self.ref_date
return floor(difftime.days / 7)
def day_of_week(self):
difftime = self-self.ref_date
return difftime.days % 7
def day_of_year(self):
return self.timetuple().tm_yday
#staticmethod
def to_GPS_date(date):
return GPS_Date(date.year, date.month, date.day, date.hour, date.minute, date.second)
#staticmethod
def now():
return GPS_Date.to_GPS_date(datetime.datetime.utcnow())
When I run the following code in python3.6 I get the correct solution:
import datetime
from GPS_Date import GPS_Date
time_string = '2019-01-01 23:59:30.0'
date_format = '%Y-%m-%d %H:%M:%S.%f'
time_1 = datetime.datetime.strptime(time_string, date_format)
time_2 = GPS_Date.to_GPS_date(time_1)
add_time = time_2 + datetime.timedelta(minutes=30)
But when I run it with python3.9 I get the following error:
add_time = time_2 + datetime.timedelta(minutes=30)
TypeError: __init__() takes from 4 to 7 positional arguments but 9 were given
I assume something has been changed between python3.6 and python3.9. I've looked at documentation but haven't found anything. Can anyone enlighten me?
datetime.datetime does have more arguments that can be passed than GPS_Date accounts for (i.e. tzinfo and fold). Why this doesn't blow up in Python3.6, I am not sure. But you don't need to override __init__ at all, since you aren't doing anything:
class GPS_Date(datetime.datetime):
ref_date = datetime.datetime(1980, 1, 6)
def gps_week(self):
difftime = self - self.ref_date
return floor(difftime.days / 7)
def day_of_week(self):
difftime = self - self.ref_date
return difftime.days % 7
def day_of_year(self):
return self.timetuple().tm_yday
#staticmethod
def to_GPS_date(date):
return GPS_Date(date.year, date.month, date.day, date.hour, date.minute, date.second)
#staticmethod
def now():
return GPS_Date.to_GPS_date(datetime.datetime.utcnow())
is perfectly fine. (Also note: If you were to do something, you need to override __new__ instead of __init__)

Call a variable in one function from another function inside a class

I am following this answer and trying to call a variable of one function from another function, but getting an error. Below is my test code.
import datetime
from datetime import timedelta
import time
class TimeTesting:
def TimeTest1(self):
T1 = datetime.datetime.now()
time.sleep(5)
print('TimeTest1 is being called')
def TimeTest2(self):
T2 = datetime.datetime.now()
TimeDiff = T2 - self.T1
print('Timetest2 has been called')
print('Time diff is {}'.format(TimeDiff))
ob = TimeTesting()
ob.TimeTest1()
ob.TimeTest2()
Below is the error that I am getting -
TimeDiff = T2 - self.T1 AttributeError: 'TimeTesting' object has no
attribute 'T1'
Can someone point me out what I am doing wrong?
You would need to define T1 as an instance variable:
self.T1 = datetime.datetime.now()
As it stands, T1 is just a local variable to method TimeTest1, and is only in scope in that method.

How can I change the datetime in my Python Atom-class, or create a setter for it?

Hi I'm new to GUI programming, so after trying PyQt for a short time I found Enaml which made the production much more easy.
I'm trying to have a widget that can change the value of a datetime.datetime object or a datetime.time object, but it turns out they are read-only. So how could I do that? Can I change the variable to have read-and-write attributes, or maybe need a setter?
My minimum working solution is:
from __future__ import print_function
import datetime
import os
from atom.api import Atom, Unicode, Range, Typed, observe, Value, Bool
class SimulationCase(Atom):
startDateTime = datetime.datetime.strptime('05.03.2015-5','%d.%m.%Y-%H')
currentDateTime = startDateTime
endDateTime = startDateTime+ datetime.timedelta(days=int(5))
incrementTime = datetime.time(1,0,0)
def main():
case = SimulationCase()
print(case.currentDateTime)
a = datetime.time(1,0,0)
print(a)
#This is where the problem occures, comment out the line under for a working solution.
case.incrementTime = a
if __name__ == '__main__':
main()
Your solution is incorrect. You use the member types to create members in your Atom class which can then be accessed and set through the normal __getattr__ mechanism.
A correct example of your sample code:
from __future__ import print_function
import datetime
import os
from atom.api import Atom, Unicode, Range, Typed, observe, Value, Bool
def default_time_factory():
return datetime.datetime.strptime('05.03.2015-5','%d.%m.%Y-%H')
class SimulationCase(Atom):
startDateTime = Typed( datetime.datetime, factory=default_time_factory )
currentDateTime = Typed( datetime.datetime, factory=default_time_factory )
endDateTime = Typed( datetime.datetime, default=default_time_factory()+datetime.timedelta(days=int5) )
incrementTime = Typed( datetime.time, default=datetime.time(1,0,0) )
def main():
case = SimulationCase()
print(case.currentDateTime)
a = datetime.time(1,0,0)
print(a)
#This now works
case.incrementTime = a
if __name__ == '__main__':
main()
I found a solution based on looking into the Property.py documentation of Nucleic Development Team Atom.
The setter could be done by adding a function with _set_variable(self,variable) and _get_variable(self):
A possible solution is therefore:
from __future__ import print_function
import datetime
import os
from atom.api import Atom, Unicode, Range, Typed, observe, Value, Bool, Property
class SimulationCase(Atom):
startDateTime = Property()
_startDateTime = Typed(datetime.datetime)
currentDateTime = Property()
_currentDateTime = Typed(datetime.datetime)
endDateTime = Property()
_endDateTime = Typed(datetime.datetime)
incrementTime = Property()
_incrementTime = Typed(datetime.time)
# Getter and setter for startDateTime
def _set_startDateTime(self,startDateTime):
self._startDateTime = startDateTime
def _get_startDateTime(self):
return self._startDateTime
# Getter and setter for currentDateTime
def _set_currentDateTime(self,currentDateTime):
self._currentDateTime = currentDateTime
def _get_currentDateTime(self):
return self._currentDateTime
# Getter and setter for endDateTime
def _set_endDateTime(self,endDateTime):
self._endDateTime = endDateTime
def _get_endDateTime(self):
return self._endDateTime
# Getter and setter for incrementTime
def _set_incrementTime(self,incrementTime):
self._incrementTime = incrementTime
def _get_incrementTime(self):
return self._incrementTime
# Populating the data
def __init__(self):
self._startDateTime = datetime.datetime.strptime('05.03.2015-5','%d.%m.%Y-%H')
self._currentDateTime = self._startDateTime
self._endDateTime = self._startDateTime + datetime.timedelta(days=int(5))
self._incrementTime = datetime.time(1,0,0)
def main():
case = SimulationCase()
print(case.currentDateTime)
print(case.incrementTime)
print(case.endDateTime)
a = datetime.time(2,0,0)
case.incrementTime = a
print(case.incrementTime)
if __name__ == '__main__':
main()

The methods I'm using are unbound?

I'm working on a calendar via Python's HTMLCalendar and Django. The functions I'm using to input data into the calendar are showing up as unbound, and therefore not working.
Here's the calendar code:
from www.wednesday.models import Event
import calendar
e = Event()
class EventCal(calendar.HTMLCalendar):
def formatday(self, day, weekday):
if day == 0:
return '<td class="noday"> </td>' # Day outside month
if day == e.dd():
return '<td class="%s">%d</p>%s</td>' % (self.cssclasses[weekday], day, e.link(), e.res())
else:
return '<td class="%s">%d</td>' % (self.cssclasses[weekday], day)
class rendCal:
c = EventCal(calendar.SUNDAY)
Here's my models.py:
from django.db import models
class Event(models.Model):
Restaurant = models.CharField(max_length=200)
LinkURL = models.CharField(max_length=200)
created = models.DateTimeField(auto_now_add=True)
DateDay = models.IntegerField(max_length=2)
def dd(self):
return '%i' % self.DateDay
def link(self):
return '%s' % self.LinkURL
def res(self):
return '%s' % self.Restaurant
And lastly, my views.py:
from django.shortcuts import render_to_response
import www.wednesday.models
from www.wednesday.cal import rendCal
import datetime as dt
def calendar(request):
now = dt.datetime.now()
cal = rendCal.c.formatmonth(now.year, now.month)
return render_to_response('cal.html', {'calendar': cal})
Everything works except for the functions from Event that are called inside the EventCal class.
Obviously I'm quite new at this.
Okay, #Marcin asked for an error, this is what I'm seeing, also I corrected the capitalization.
TypeError at /calendar/
unbound method dd() must be called with Event instance as first argument (got nothing instead)
cal.py in formatday, line 9
The environment variables in EventCal from Event are showing up blank, I'm pretty sure that's why I'd been getting the needs int not str error. When I change e.dd() to a static number, it returns everything but e.link() and e.res().
dd() is a method of an instance of the class.
You call it like this:
e = Event()
x = e.dd()
You can't apply dd to Event itself.
I am not sure what exactly you are trying to do, so I am not sure how you need to modify your code.
In formatday you have:
if day == 0:
but also:
if day == Event.dd():
and Event.dd() returns a string.
So, is day an int or a string?

Categories

Resources