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

Python中如何使用Timestamp作为输入?二维Timestamp数组输入格式问询

Working with Pandas Timestamp as Input in Python (Including 2D Arrays)

Great question! When working with timestamps in Python, pandas' pd.Timestamp is the go-to object for robust date-time handling. Let's walk through both your questions step by step.

1. Using a Single Timestamp as Function Input

First, you'll want to make sure your function explicitly accepts pd.Timestamp objects—either via type hints for clarity, or runtime checks to enforce the type. Here's a straightforward example:

import pandas as pd

def process_timestamp(ts: pd.Timestamp):
    """Function that operates on a single Timestamp"""
    print(f"Input timestamp: {ts}")
    print(f"Extracted year: {ts.year}, month: {ts.month}")

# Create a Timestamp object and pass it to the function
my_ts = pd.Timestamp("2024-05-20 14:30:00")
process_timestamp(my_ts)

# You can also create Timestamps from integers (e.g., Unix time)
unix_ts = pd.Timestamp(1716193800, unit='s')
process_timestamp(unix_ts)

If you want to enforce that the input is definitely a Timestamp (not a string or datetime.datetime), add a quick check inside the function:

def process_timestamp(ts: pd.Timestamp):
    if not isinstance(ts, pd.Timestamp):
        raise TypeError(f"Expected pd.Timestamp, got {type(ts)} instead")
    # Rest of your logic...

2. Constructing a 2D Array of Timestamp Objects

For a 2D input (like a list of lists where each element is a pd.Timestamp), you just need to explicitly wrap each date value with pd.Timestamp() when building the array. This ensures every element is the correct type and avoids syntax errors.

Here's how to build the array and use it in a function that finds the overall date range:

import pandas as pd

def find_overall_date_range(timestamp_2d: list[list[pd.Timestamp]]):
    """Parse a 2D array of Timestamps to find min and max dates"""
    # First, flatten the 2D array to collect all Timestamps
    all_timestamps = [ts for row in timestamp_2d for ts in row]
    
    if not all_timestamps:
        return None, None  # Handle empty array case
    
    min_date = min(all_timestamps)
    max_date = max(all_timestamps)
    return min_date, max_date

# Construct your 2D Timestamp array
timestamp_grid = [
    [pd.Timestamp("2024-01-01"), pd.Timestamp("2024-01-15")],
    [pd.Timestamp("2024-02-01"), pd.Timestamp("2024-02-28")],
    [pd.Timestamp("2024-03-10"), pd.Timestamp("2024-03-20")]
]

# Call the function and print results
start, end = find_overall_date_range(timestamp_grid)
print(f"Found date range: {start} to {end}")

Alternative: Using NumPy Arrays (If Preferred)

If you're working with NumPy, you can create a 2D datetime64 array and convert it to pd.Timestamp objects:

import numpy as np
import pandas as pd

# Create a NumPy 2D datetime array
np_datetime_grid = np.array([
    ["2024-01-01", "2024-01-15"],
    ["2024-02-01", "2024-02-28"]
], dtype="datetime64[ns]")

# Convert to a list of lists of pd.Timestamp
timestamp_grid_from_np = [[pd.Timestamp(ts) for ts in row] for row in np_datetime_grid]

Key Notes to Avoid Errors

  • Never pass raw strings: If you just write "2024-05-20" in your array, it's a string, not a Timestamp—always wrap dates with pd.Timestamp().
  • Type hints help: Using list[list[pd.Timestamp]] as the input type hint makes your function's expectations clear to other developers (and tools like linters).
  • Validate inputs: Adding isinstance checks in your function ensures you catch non-Timestamp inputs early, preventing unexpected bugs later.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 10:09:26