Skip to content
Advertisement

How do I implement the datetime module into my code?

from datetime import datetime

class User:
    def __init__(self, username, mail, date_of_birth, gender, password):
        self.username = username
        self.mail = mail
        self.date_of_birth = datetime.date(date_of_birth)
        self.gender = gender
        self.password = password

    def get_username(self):
        return self.username

    def get_mail(self):
        return self.mail

    def get_date_of_birth(self):
        return self.date_of_birth
    def get_gender(self):
        return self.gender

    def get_password(self):
        self.password



Matt = User("Matterson", "matt@gmail.com", 21.12.1999 , "Password987")

So how do I make the string a date?

The error:

Matt = User("Matterson", "matt@gmail.com", 21.12.1999 , "Password987")
                                                    ^
SyntaxError: invalid syntax

Advertisement

Answer

When you’re creating your object you have to enclose the value inside quotes:

User("Matterson", "matt@gmail.com", "21.12.1999", "Password987")

Just 21.12.1999 by itself isn’t a valid Python definition of anything.

You can then use strptime of the datetime.datetime module to parse it into a datetime, and retrieve the date from that value:

self.date_of_birth = datetime.datetime.strptime(date_of_birth, "%d.%m.%Y").date()

The %d corresponds to the day, the %m the month and %Y to the year in the string being sent in. Calling date() on the datetime drops the time-part and returns a pure date instead.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement