Python datetime列拆分工具函数报错求助:NameError问题
Hey there! Let's break down what's going wrong and how to fix it, plus make your function even better.
First: Fixing the NameError
The error you're seeing is super straightforward—when you called datetime_to_cols(train, dateCreated), you passed dateCreated as a bare name instead of a string. Python interprets bare names as variables, but you never defined a variable called dateCreated (it's just the name of your DataFrame column).
The fix is simple: wrap the column name in quotes
datetime_to_cols(train, 'dateCreated')
Second: Optimizing Your Function
Your core logic works, but we can make the function cleaner, more robust, and easier to maintain. Here's an improved version:
import pandas as pd def datetime_to_cols(df, col_to_convert): # Check if the target column exists in the DataFrame if col_to_convert not in df.columns: raise ValueError(f"Oops! Column '{col_to_convert}' doesn't exist in your DataFrame.") # Verify the column is actually a datetime type if not pd.api.types.is_datetime64_any_dtype(df[col_to_convert]): raise TypeError(f"Column '{col_to_convert}' isn't a datetime type. Convert it first with pd.to_datetime(df['{col_to_convert}'])!") # Define the time components we want to extract time_parts = [('year', 'year'), ('month', 'month'), ('day', 'day'), ('hour', 'hour'), ('minute', 'minute'), ('second', 'second')] # Loop through each component to create new columns for part_name, dt_attr in time_parts: # Use underscores in new column names for better readability (e.g., dateCreated_year) new_col = f"{col_to_convert}_{part_name}" df[new_col] = df[col_to_convert].dt.__getattribute__(dt_attr) return df # Optional: return the modified DataFrame for method chaining
Key improvements here:
- Error checking: We add checks to make sure the column exists and is a datetime type, so you get clear, actionable error messages instead of confusing crashes later.
- DRY (Don't Repeat Yourself) code: Instead of writing the same line 6 times, we use a loop. If you ever want to add more time components (like
weekdayorquarter), just add a tuple to thetime_partslist. - Readable column names: Using underscores (e.g.,
dateCreated_year) makes the new columns easier to read thandateCreatedyear. If you prefer your original naming style, just changef"{col_to_convert}_{part_name}"tof"{col_to_convert}{part_name}".
One More Thing: Ensure Your Column is Datetime Type
If you haven't already converted dateCreated to a datetime type, run this first:
train['dateCreated'] = pd.to_datetime(train['dateCreated'])
That should get everything working smoothly!
内容的提问来源于stack exchange,提问作者Milap

