Konwertuj typ kolumny DataFrame z string na datetime, format dd / mm / RRRR

Jak mogę przekonwertować kolumnę DataFrame łańcuchów (w dd / mm / RRRR format) do dat?

Author: smci, 2013-06-16

4 answers

Najprostszym sposobem jest użycie to_datetime:

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

Oferuje również dayfirst argument dla czasów europejskich (ale uważaj to nie jest ścisłe ).

Tutaj jest w akcji:

In [11]: pd.to_datetime(pd.Series(['05/23/2005']))
Out[11]:
0   2005-05-23 00:00:00
dtype: datetime64[ns]

Możesz przekazać określony format :

In [12]: pd.to_datetime(pd.Series(['05/23/2005']), format="%m/%d/%Y")
Out[12]:
0   2005-05-23
dtype: datetime64[ns]
 535
Author: Andy Hayden,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-12-24 22:47:55

Jeśli kolumna daty jest ciągiem znaków w formacie '2017-01-01' możesz użyć pandas astype, aby przekonwertować go na datetime.

df['date'] = df['date'].astype('datetime64[ns]')

Lub użyj datetime64 [D], jeśli chcesz dokładności dnia, a nie nanosekund

print(type(df_launath['date'].iloc[0]))

<class 'pandas._libs.tslib.Timestamp'> tak samo jak w przypadku pandy.to_datetime

Możesz spróbować z innymi formatami, a następnie '%Y - % m - % d', ale przynajmniej to działa.

 41
Author: sigurdb,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-06-26 16:11:55

Możesz użyć następujących formatów, jeśli chcesz określić trudne formaty:

df['date_col'] =  pd.to_datetime(df['date_col'], format='%d/%m/%Y')

Więcej szczegółów na format tutaj:

 36
Author: Ekhtiar,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-10-11 21:16:28

Jeśli masz mieszankę formatów w swojej dacie, nie zapomnij ustawić infer_datetime_format=True, aby ułatwić życie.

df['date'] = pd.to_datetime(df['date'], infer_datetime_format=True)

Źródło: pd. to_datetime

Lub jeśli chcesz niestandardowe podejście:

def autoconvert_datetime(value):
    formats = ['%m/%d/%Y', '%m-%d-%y']  # formats to try
    result_format = '%d-%m-%Y'  # output format
    for dt_format in formats:
        try:
            dt_obj = datetime.strptime(value, dt_format)
            return dt_obj.strftime(result_format)
        except Exception as e:  # throws exception when format doesn't match
            pass
    return value  # let it be if it doesn't match

df['date'] = df['date'].apply(autoconvert_datetime)
 5
Author: otaku,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-12-09 01:56:25