Dates And Times In Python — The Time Class | Dataquest
My Code:
for row in potus:
the_time=row[2]
the_time=dt.time(the_time)
appt_times.append(the_time)
Replace this line with the output/error
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-1-a427b0de805c> in <module>
12 for row in potus:
13 the_time=row[2]
---> 14 the_time=dt.time(the_time)
15 appt_times.append(the_time)
TypeError: an integer is required (got type datetime.datetime)
I dont’t understand why the correct code is
for row in potus:
the_time=row[2]
the_time=the_time.time()
appt_times.append(the_time)
``
Why is there no dt.time(the_time). I thought we had to specify that we are using the time module since we imported it as dt such that
```import datetime as dt```
Hello @hliu19922019
Please post a link to this task.
If you move a little bit back to screen 5/12:
import datetime as dt
pattern = '%m/%d/%y %H:%M'
for one in potus:
a = one[2]
b = dt.datetime.strptime(a, pattern)
one[2]= b
We change the string object in index position 2 to datetime object.
On screen 7/12, we want to extract the time part of the datetime object. So we apply the date()
function/method. You have applied it as a function, and to do so correctly use:
for row in potus:
the_time=row[2]
the_time=dt.datetime.time(the_time)
appt_times.append(the_time)
You have imported datetime as dt
. Next, you have to get the datetime
class from this module like this: dt.datetime
. Next you get the time
function like this dt.datetime.date
.
You can also complete the task by using the time
method:
for one in potus:
a = one[2]
b = a.time()
appt_times.append(b)
I’m sorry but I’m still not understanding it’s “b=a.time()” instead of “b=dt.time(a)” since we have to call the datetime module right since we imported datetime as “dt”
You can use both, but if you want to use the latter, you have to call it correctly.
It is datetime.datetime.time
. Since you imported the first datetime
as dt
, it now become: dt.datetime.time
That makes sense but then why does the_time. time() work? I haven’t called the dt module yet.
On screen 5, you changed it to a datetime object.
Let me illustrate with a class. Say you have a class called School
and it has a method student
.
school = School ()
students = school.student()
When you initialise the class School
, you can call it’s student
method later.
Substitute school
class with datetime.datetime
class and student
method with time
method.
On screen 5, you changed to a datetime
object. On screen 7, you called its time
method.