Home > database >  How do I convert this date from a string to datetime in Pandas?
How do I convert this date from a string to datetime in Pandas?

Time:10-13

I am trying to extract datetime from a string in a pandas dataframe. 'Date' below is in string (DK-locale)

Message date DateConverted
blabla 9. okt. 2021 11.41 NaT
blabla 9. okt. 2021 11.38 NaT
blabla 9. okt. 2021 11.01 NaT

My cell in jupyter trying to convert looks like this:

import pandas as pd

df = pd.read_csv("messages.csv", sep=",")
df['DateConverted'] = pd.to_datetime(df['Date'], errors='coerce' ,format='%d. %b. %Y %I.%M'

I've tried a few variations on the format, but nothing yields results. Does anyone know what I'm missing?

CodePudding user response:

You can try:

>>> import locale
>>> locale.setlocale(locale.LC_ALL, 'da_DK')
'da_DK'
>>>
>>> df['DateConverted'] = pd.to_datetime(df['date'], format='%d. %b. %Y %I.%M')
>>>
>>> df
  Message                date       DateConverted
0  blabla  9. okt. 2021 11.41 2021-10-09 11:41:00
1  blabla  9. okt. 2021 11.38 2021-10-09 11:38:00
2  blabla  9. okt. 2021 11.01 2021-10-09 11:01:00
>>>
>>> df.dtypes
Message                  object
date                     object
DateConverted    datetime64[ns]
dtype: object
  • Related