You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python Pandas中无法将Series类型转为string及提取日期去除时间后缀问题求助

How to Extract Date Part from DateTime Strings in a Pandas DataFrame

Hey Lisa, let's sort out this date trimming problem for you! It sounds like you've already tried converting the column to string types, but haven't followed through with the actual string manipulation to get rid of the time suffix. Here are three straightforward, reliable methods to keep just the date part:

Method 1: Split the String by Space

Since each entry in your column follows the pattern [date] [time], you can split the string at the space character and take the first part:

import pandas as pd
df['id'] = df['id'].astype(str).str.split(' ').str[0]

This converts the Series to string type first, splits each value into a list of two elements (date and time), then extracts the first element (the date).

Method 2: Slice the String Directly

If your date format is consistently dd.mm.yyyy (10 characters long), you can directly slice the first 10 characters of each string:

df['id'] = df['id'].astype(str).str[:10]

This is a faster approach than splitting, especially if you're working with a large dataset.

Instead of treating the values as plain strings, converting them to pandas datetime objects gives you more flexibility for future date-related operations. You can then extract the date part as either a date object or a formatted string:

# Convert to datetime and extract date object
df['id'] = pd.to_datetime(df['id']).dt.date

# Or convert to datetime and format as a string (matches your original date format)
df['id'] = pd.to_datetime(df['id']).dt.strftime('%d.%m.%Y')

Pandas' to_datetime function will automatically recognize your dd.mm.yyyy HH:MM format, so no need to specify a format string here (though you can add format='%d.%m.%Y %H:%M' for extra clarity if you want).

One quick note: Your earlier attempts only converted the column to string types but didn't perform the actual trimming step—adding the split/slice/datetime extraction is what gets you the date-only values you need.

内容的提问来源于stack exchange,提问作者Lisa

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 18:27:31