-3

I am working on a project , where I have dictionary with column date called "starttime" .. I need to extract month , hour and year , day of the week. I am stuck for now I have the below code .

   {if city =='NYC':
        datn = datum[('starttime')]
        datn = dt.strptime(datn,"%m/%d/%y %H:%M:%S")
        hour = dt.strftime(datn,"%H")
        year = dt.strftime(datn,"%y")
    elif city == 'Chicago':
    datc = datum[('starttime')]
    datc = dt.strptime(datc,"%m/%d/%y %H:%M")
    month = dt.strftime(datc,"%m")
    hour = dt.strftime(datc,"%H")
    year = dt.strftime(datc,"%y")
    else:
    datw = datum[('start date')]
    datw = dt.strftime (datw,"%m")
    hour = dt.strftime(datw,"%H")
    year = dt.strftime(datw,"%y")
                              
return (month, hour, day_of_week)
   } 

my import statements are on the top of my code , as below:

from datetime import datetime
codeforester
  • 39,467
  • 16
  • 112
  • 140
Eithar
  • 97
  • 1
  • 7

2 Answers2

10

strptime translates to

"parse (convert) string to datetime object."

strftime translates to

"create formatted string for given time/date/datetime object according to specified format."

Why do you need strftime?

This is what a datetime object looks like: (2015, 7, 19, 22, 7, 44, 377000)

To someone who isn't quite familiar with this format, with the exception of the year, what's written up there is not immediately intuitive. So you probably would be better off with something like Sun, 19 July, 2015. That's what strftime is used for. You simply need to learn the proper formatting strings.

One Good Link over SO read about this !

Karn Kumar
  • 8,518
  • 3
  • 27
  • 53
1

strptime converts the string to a datetime object.

strftime creates a formatted string for given time/date/datetime object according to specified format by the user

you would use strftime to convert a datetime object like this: datetime (2018, 10, 20, 10, 9, 22, 120401) to a more readable format like "20-10-2018" or 20th of October 2018.

Dominique Paul
  • 1,623
  • 2
  • 18
  • 31