Explain: The Time Class

Screen Link:
https://app.dataquest.io/m/353/working-with-dates-and-times-in-python/7/the-time-class

Please how did you get the output as “1900-01-01 08:00:00” . I tried it and it showed error "ValueError: time data ‘8:00’ does not match format ‘%H,%M’ ". But when i copied your code and pasted there was no error. My question is, is there any embedded code in the learn section that made your code work and mine didn’t.

This means you are not parsing the required format. your format is %H,%M and looking at the one provided the format is %H:%M. You inserted a , where : is required.

Everything works fine in my console.

Thanks, is working now. But i am still confused . We passed a variable that has “8:00” ie hour and min. Where does the “1900-01-01” come from which is year, month and day.

The datetime.strptime() constructor returns a datetime object. So, when we parse time it instantiates the date and if we code for date then it would automatically instantiates the time to zero. Means it considers both date as well as time.

Input


from datetime import datetime

date_string = "21 June, 2018"

date_object = datetime.strptime(date_string, "%d %B, %Y")

Output

2018-06-21 00:00:00

Sorry for the late reply, i have been sick. In your solution, you specifies day, month and year which is date_string. Check mine: time_str = “8:00” it instantiates just hr and mine which is passed to dt.datetime.strptime(). Now look at the output 1900-01-01 08:00:00. The output included not just the hr and mins i passed but also year,month and day of which i didn’t passed. My Question is how did that happen?

Hope you are doing well now.
While using strptime, even if you don’t pass date along with time a default date would be printed in python. This is because it is used to pass both.
If you want to consider only time part refer the code below. The below code might make things clear.

Yes, I am better now. Thanks for asking.

I understand it now. Thank You for your patience

1 Like