[Tutor] Datetime object as a class property

Marc Tompkins marc.tompkins at gmail.com
Mon Aug 31 13:54:33 EDT 2020


On Mon, Aug 31, 2020 at 10:32 AM John Weller <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 = '' which I can
> then populate in an instance of my class with 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 = name
    self.sunrise = datetime.strptime(sunrise, "%H:%M:%S")

data = Data()

print(data.name)
print(data.sunrise)

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

print(data.name)
print(data.sunrise)


More information about the Tutor mailing list