how to convert string to date pandas python TypeError: strptime() takes no keyword arguments

10,194

Pass the format string as a positional argument.

>>> import time
>>> def convertdate(dstring):
...     return time.strptime(dstring, '%Y-%m-%d')
...
>>> convertdate('2013-03-02')
time.struct_time(tm_year=2013, tm_mon=3, tm_mday=2, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=5, tm_yday=61, tm_isdst=-1)

BTW, time.strptime returns time.struct_time. Its attributes are prefixed with tm_.

More preferably you can use datetime.datetime.strptime:

>>> import datetime
>>> import pandas as pd
>>>
>>> def convertdate(dstring):
...     return datetime.datetime.strptime(dstring, '%Y-%m-%d')
...
>>> dt = convertdate('2013-03-02')
>>> dt
datetime.datetime(2013, 3, 2, 0, 0)
>>> pd.DataFrame([{'year': dt.year, 'month': dt.month, 'day': dt.day}])
   day  month  year
0    2      3  2013
Share:
10,194
yoshiserry
Author by

yoshiserry

Updated on June 04, 2022

Comments

  • yoshiserry
    yoshiserry almost 2 years

    I have a dataframe with some text dates in them. I would like to return the dates: year, month and day in separate columns. But in order to do that I need to first convert the text(from excel) to a date.

    The code I have now is

    def convertdate(dstring):
        dt = time.strptime(dstring, date_format='%Y-%m-%d')
        return dt
    

    However it returns an: TypeError: strptime() takes no keyword arguments

    Then instead of three separate functions for creating three separate columns, one for year, one for month, one for day.

    Once the string is a date time object (dt), I believe the code is: return dt.year, return dt.month, return dt.day.

    I would like one function which adds three columns to my dataframe, is this possible?

  • yoshiserry
    yoshiserry about 10 years
    Hi Thanks, what is the difference between your two answers, time.strptime, and datetime.datetime.strptime?
  • falsetru
    falsetru about 10 years
    @yoshiserry, They returns different object. time.strptime returns time.struct_time object, while datetime.datetime.strptime returns datetime object. They have different attributes.