Search code examples
pythonpandasdatestring-to-datetime

pd.to_datetime() with spanish locale system


d1 = today.strftime("%b-%y")
print("d1 =", d1)

d1 = ene.-21

But the variable I want to convert in my data set is Jan-21.

My code

data['date_text_DATE'] = pd.to_datetime(data['date_text'], format = '%b-%y')

The error I got:

ValueError: time data 'Jan-21' does not match format '%b-%y' (match)

It does not convert the text into date format.


Solution

  • EDIT: author noted in comments below the issue was due to their Python/R environment.

    I'm not sure what you're trying to accomplish with the d1 variable but the sample I created works fine for me.

    I suspect your column has a value within it not conforming to a date pattern. Can you share the whole dataset or that column

    Here is what I did.

    df = pd.DataFrame(data={'a':'Jan-21'}, index=[0])
    pd.to_datetime(df['a'], format='%b-%y')
    

    And it worked fine.

    You might want to check your encoding isn't doing something weird, maybe Cyrillic alphabet or something. The following should return 425: sum([ord(l) for l in 'Jan-21'])

    Where 'Jan-21' should be your cell value from the Pandas Dataframe and not, obviously, what I just typed above.

    EDIT 2: More details regarding the issue, from comments, that helped OP.

    df['a'].dt.strftime(date_format='%b-%Y') will convert to datetime any values of the format mmm-yy. All pandas series have a .dt accessor which gives you a lot of datetime related functions such as being able to return .weekofyear or .second, and .strftime (string format time) is a very common Python method which allows the string formatting of a datetime utilising the format style you require. You can change the dash for forward-slash, etc. You can see all the format options at this link: https://docs.python.org/3/library/datetime.html#strftime-and-strptime-format-codes

    More on .dt accessor: https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.dt.strftime.html

    ALSO

    If you are getting errors with datetime and it seems absolutely sure you are doing the correct thing (such as the example given in Edit 2) then reinstall and upgrade your datetime module by doing, in order:

    1. pip uninstall datetime
    2. pip install datetime
    3. pip install datetime --upgrade