Python Dates and Times in Python Dates and Times strftime & strptime

Kohei Ashida
Kohei Ashida
4,881 Points

the difference between to_string and from_string functions.

I solved this challenge with following lines of code but I couldn't get why to_string function works with "return my_datetime.strftime('%d %B %Y')" not "return datetime.datetime.strftime(my_datetime, '%d %B %Y')" like as from_string function does.

Is this because strftime is an instance method and strptime is a class method?

import datetime

def to_string(my_datetime):
    return my_datetime.strftime('%d %B %Y') # Shoudn't it be like "datetime.datetime.strftime(my_datetime, '%d %B %Y')"?

def from_string(my_date, my_format):
    return datetime.datetime.strptime(my_date, my_format)

1 Answer

Steven Parker
Steven Parker
203,736 Points

You're exactly right, an instance method has access to the instance it is called on, and doesn't need to have it passed as an argument.

Kohei Ashida
Kohei Ashida
4,881 Points

Thanks a lot! it cleared up my eyes!