0

I want to convert a string with this format "25 de mayo de 2023 14:53 hs." into a datetime, I've used the method:

df['Fecha_de_venta'] = pd.to_datetime(df['Fecha_de_venta'])

but the output says the string format is unexpected. Is there any method I can use in order to transform it into a know string to then transform it into a datetime.

mjmoralesf
  • 15
  • 6
  • 1
    It seems like your datetime format doesn't match the format that pandas expects. I'd look into [python regular expressions](https://docs.python.org/3/library/re.html) or python's datetime function [strptime](https://docs.python.org/3/library/datetime.html#strftime-and-strptime-format-codes) is a regex for datetimes. – mickey May 30 '23 at 14:56
  • 1
    Does this answer your question? [Parse date and change format from spanish](https://stackoverflow.com/questions/42760474/parse-date-and-change-format-from-spanish) – tevemadar May 30 '23 at 15:01

2 Answers2

3

To convert a string with the format "25 de mayo de 2023 14:53 hs." into a datetime object, you can use the strptime function from the datetime module.

import locale
from datetime import datetime

date_string = "25 de mayo de 2023 14:53 hs."
date_format = "%d de %B de %Y %H:%M hs."

# Set the appropriate locale for month names
locale.setlocale(locale.LC_TIME, 'es_ES.UTF-8')

# Parse the string into a datetime object
datetime_object = datetime.strptime(date_string, date_format)

print(datetime_object)

[EDIT] If you want to convert a full column of data, use this code instead:

import locale
from datetime import datetime
import pandas as pd

# Set the appropriate locale for month names
locale.setlocale(locale.LC_TIME, 'es_ES.UTF-8')

# Define the conversion function
def convert_to_datetime(date_string):
    date_format = "%d de %B de %Y %H:%M hs."
    return datetime.strptime(date_string, date_format)

# Create a sample DataFrame
data = {'Fecha_de_venta': ['25 de mayo de 2023 14:53 hs.', '26 de junio de 2023 10:30 hs.', '27 de julio de 2023 18:45 hs.']}
df = pd.DataFrame(data)

# Apply the conversion function to the column
df['Fecha_de_venta'] = df['Fecha_de_venta'].apply(convert_to_datetime)

print(df['Fecha_de_venta'])
Tobias
  • 116
  • 8
0

For using it directly into pandas like you asked.

Try this:

import locale
locale.setlocale(locale.LC_ALL, "es_ES.UTF-8")

import pandas as pd
df['Fecha_de_venta'] = pd.to_datetime(df['Fecha_de_venta'], format="%d de %B de %Y %H:%M hs.")

Check this screenshot