JavaScript
x
28
28
1
from datetime import datetime
2
3
class User:
4
def __init__(self, username, mail, date_of_birth, gender, password):
5
self.username = username
6
self.mail = mail
7
self.date_of_birth = datetime.date(date_of_birth)
8
self.gender = gender
9
self.password = password
10
11
def get_username(self):
12
return self.username
13
14
def get_mail(self):
15
return self.mail
16
17
def get_date_of_birth(self):
18
return self.date_of_birth
19
def get_gender(self):
20
return self.gender
21
22
def get_password(self):
23
self.password
24
25
26
27
Matt = User("Matterson", "matt@gmail.com", 21.12.1999 , "Password987")
28
So how do I make the string a date?
The error:
JavaScript
1
4
1
Matt = User("Matterson", "matt@gmail.com", 21.12.1999 , "Password987")
2
^
3
SyntaxError: invalid syntax
4
Advertisement
Answer
When you’re creating your object you have to enclose the value inside quotes:
JavaScript
1
2
1
User("Matterson", "matt@gmail.com", "21.12.1999", "Password987")
2
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:
JavaScript
1
2
1
self.date_of_birth = datetime.datetime.strptime(date_of_birth, "%d.%m.%Y").date()
2
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.