如何拆分Timestamp为指定格式的日期和时间列?解决格式转换报错
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().
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.
Extract Date in
dd/mm/yyyyformat
Usedt.strftime()to format the parsed datetime into your desired date string:df['Date'] = df['DateTime'].dt.strftime('%d/%m/%Y')Extract Time in
HH:MMformat
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:
| DateTime | Date | Time |
|---|---|---|
| 2015-12-31 22:45:00 | 31/12/2015 | 22:45 |
| 2016-01-01 09:30:00 | 01/01/2016 | 09:30 |
Why Your Initial Methods Didn't Work
pd.to_datetime(df['DateTime']).dt.datereturns a Pythondateobject, which by default displays asyyyy-mm-ddwhen converted to a string.pd.to_datetime(df['DateTime']).dt.timereturns a Pythontimeobject, 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

