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

如何拆分Timestamp为指定格式的日期和时间列?解决格式转换报错

Fixing Date/Time Extraction from Timestamp in Pandas

Hey there, let's work through your problem step by step—you're trying to split a DateTime field (like 31/12/2015 22:45) into separate Date and Time columns with specific formats, but you're running into formatting issues and errors. Here's how to fix it:

Why You Got the ValueError

When you used pd.to_datetime(df['DateTime'], format='%d/%m/%Y'), the format parameter only accounts for the date portion (dd/mm/yyyy) of your timestamp. Since your DateTime strings include a time component (like 22:45), pandas can't parse that extra data, hence the "unconverted data remains" error.

The Solution: Parse First, Format Second

Instead of pulling out date/time objects (which have fixed default string representations), parse the full timestamp correctly, then format it into the string structure you need using strftime().

  1. First, parse the complete DateTime string
    Use the full format that matches your input (date + time) to avoid parsing errors:

    # Parse the DateTime column with the correct full format
    df['DateTime'] = pd.to_datetime(df['DateTime'], format='%d/%m/%Y %H:%M')
    

    This ensures pandas correctly interprets both the date and time parts of your timestamp.

  2. Extract Date in dd/mm/yyyy format
    Use dt.strftime() to format the parsed datetime into your desired date string:

    df['Date'] = df['DateTime'].dt.strftime('%d/%m/%Y')
    
  3. Extract Time in HH:MM format
    Similarly, format the time part to exclude seconds:

    df['Time'] = df['DateTime'].dt.strftime('%H:%M')
    

Example Result

If your original DataFrame looks like this:

DateTime
31/12/2015 22:45
01/01/2016 09:30

After running the code above, you'll get:

DateTimeDateTime
2015-12-31 22:45:0031/12/201522:45
2016-01-01 09:30:0001/01/201609:30

Why Your Initial Methods Didn't Work

  • pd.to_datetime(df['DateTime']).dt.date returns a Python date object, which by default displays as yyyy-mm-dd when converted to a string.
  • pd.to_datetime(df['DateTime']).dt.time returns a Python time object, which includes seconds (even if your input didn't have them, it will show :00).

Using strftime() gives you full control over the output format, exactly matching what you need.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 11:21:33