[Tutor] Datetime object as a class property

John Weller john at johnweller.co.uk
Mon Aug 31 14:01:52 EDT 2020


Many thanks.

 

John

 

John Weller

01380 723235

07976 393631

 

From: Marc Tompkins <marc.tompkins at gmail.com> 
Sent: 31 August 2020 18:55
To: john at johnweller.co.uk
Cc: tutor at python.org
Subject: Re: [Tutor] Datetime object as a class property

 

On Mon, Aug 31, 2020 at 10:32 AM John Weller <john at johnweller.co.uk <mailto:john at johnweller.co.uk> > wrote:

I have an instance of a class called, say, data.  I know I can create a
property, name, in the class as a string with self.name <http://self.name>  = '' which I can
then populate in an instance of my class with data.name <http://data.name>  = 'John'.  How do I
create datetime object, eg sunrise, so that in the code I can put
data.sunrise = datetime.strptime("05:45:00", "%H:%M:%S").  Self.sunrise = ?

 

Here's an example with default values for name and sunrise:

from datetime import datetime

class Data(object):
  def __init__(self, name="Nemo", sunrise="06:00:00"):
    self.name <http://self.name>  = name
    self.sunrise = datetime.strptime(sunrise, "%H:%M:%S")
  
data = Data()

print(data.name <http://data.name> )
print(data.sunrise)

data = Data("John", "05:45:00")

print(data.name <http://data.name> )

print(data.sunrise) 



More information about the Tutor mailing list