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

Pandas日期时间列解析求助:自定义编码转标准格式

Solution for Parsing Numeric Date/Time Columns to Datetime in Pandas

Got it, let's fix this datetime parsing issue step by step. The core problem with your initial code is that it didn't account for the sequential day/time logic behind those numeric values—you can't parse them directly with a simple %d format string. Here's a working, straightforward approach:

Step 1: Convert columns to numeric types

First, we need to turn the object-type Date and Time columns into integers so we can calculate proper time offsets:

import pandas as pd

# Convert object columns to integers (handle any parsing errors gracefully if needed)
df['Date'] = df['Date'].astype(int)
df['Time'] = df['Time'].astype(int)

Step 2: Define the base date for your Date sequence

Since 195 maps to 01/01/2009, we need to find the starting date of the sequence (the date that would correspond to Date=1). We calculate this by subtracting 194 days from 01/01/2009 (because 195 is 194 days after the base date):

base_date = pd.to_datetime('2009-01-01') - pd.Timedelta(days=195 - 1)

Step 3: Map numeric Date values to actual dates

Now we can convert each numeric Date value to its corresponding real date by adding the day offset to our base date:

# Subtract 1 because base_date is day 1; adding 194 days gives us 01/01/2009 for Date=195
df['date_part'] = base_date + pd.to_timedelta(df['Date'] - 1, unit='D')

Step 4: Map numeric Time values to time offsets

Your Time column uses 30-minute intervals, where 1 = 00:00:00–00:29:59. Based on your example (wanting 00:30 for Time=1), you're targeting the end time of each interval. We calculate the time offset like this:

# For end time of the interval (matches your example: 1 → 00:30)
df['time_offset'] = pd.to_timedelta(df['Time'] * 30, unit='m')

# Uncomment below if you want the start time instead (1 → 00:00)
# df['time_offset'] = pd.to_timedelta((df['Time'] - 1) * 30, unit='m')

Step 5: Combine and format the final datetime

Merge the date part and time offset to get a full datetime column, then format it to your preferred string format:

# Create the full datetime column
df['datetime'] = df['date_part'] + df['time_offset']

# Format to your desired string (e.g., "01,01,2009 00:30")
df['datetime_formatted'] = df['datetime'].dt.strftime('%d,%m,%Y %H:%M')

Example Output

For a row with Date=195 and Time=1, this will produce:

  • date_part: 2009-01-01
  • time_offset: 0 days 00:30:00
  • datetime: 2009-01-01 00:30:00
  • datetime_formatted: 01,01,2009 00:30

Which perfectly matches your expected result!


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.09 14:47:43