Strptime and strftime

can anyone please brief me about the difference between those two?
at times it gets confusing which one to use because both have similar arguments.
explanation with example will make it good

1 Like

In short, strptime change string to datetime, strftime change datetime to string

  • string --> datetime.datetime

    eg_2 = dt.datetime.strptime("24/12/1984","%d/%m/%Y")
    • datetime.datetime --> string

      dt_object = dt.datetime(1984,12,24)
      dt_string = dt_object.strftime("%d/%m/%Y")

To remember what function does what, I’ve used the following mnemonic technique:

  1. strptime - string parse time - from string parse time - strPtime
  2. strftime - string from time - make string from time - strFtime

Hope this may help.


One practical situation you need this is when you want to protect the structure of datetime types generated by pandas from being destroyed when saved and opened through a format like csv.
Although df.to_csv and pd.read_csv will automatically convert datetimes to strings for you, manually turning it to a string in an exact form you want with strftime prevents unexpected problems, possibly with other applications like excel. However this is just something to keep in mind so you know what to do when things go wrong or when trying to build better pipelines