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

技术咨询:如何将数据解析为指定格式?能否用DataFrame转换时间格式?

Absolutely! Converting that datetime format is totally doable with pandas (using DataFrames) or even Python's built-in tools. Let me break down both approaches for you:

Using Pandas DataFrame

If you're working with tabular data in a DataFrame, this is the most straightforward way:

import pandas as pd

# Example DataFrame with your datetime strings
df = pd.DataFrame({'raw_time': ['2018-03-31 15:58', '2021-07-12 08:15', '2023-01-05 23:40']})

# Step 1: Convert the string column to pandas datetime objects
df['raw_time'] = pd.to_datetime(df['raw_time'])

# Step 2: Format to the desired ISO 8601 format with UTC suffix ('Z')
df['formatted_time'] = df['raw_time'].dt.strftime('%Y-%m-%dT%H:%M:%SZ')

# Check the result
print(df)

This will output a new column where each timestamp looks like 2018-03-31T15:58:00Z. A quick note: if your original times are in a local timezone (not UTC), make sure to localize and convert to UTC first to avoid mislabeling with the 'Z' suffix. For example:

# If raw times are in 'America/New_York' timezone
df['raw_time'] = df['raw_time'].dt.tz_localize('America/New_York').dt.tz_convert('UTC')
df['formatted_time'] = df['raw_time'].dt.strftime('%Y-%m-%dT%H:%M:%SZ')
Using Python's Built-in datetime Module

If you don't need a DataFrame and just want to process individual strings or small lists:

from datetime import datetime

# Single timestamp example
original_time = '2018-03-31 15:58'
# Parse the string into a datetime object
dt = datetime.strptime(original_time, '%Y-%m-%d %H:%M')
# Format to the target string
formatted_time = dt.strftime('%Y-%m-%dT%H:%M:%SZ')

print(formatted_time)  # Output: 2018-03-31T15:58:00Z

For a list of timestamps, you can wrap this in a list comprehension:

time_list = ['2018-03-31 15:58', '2020-09-18 10:30']
formatted_list = [datetime.strptime(t, '%Y-%m-%d %H:%M').strftime('%Y-%m-%dT%H:%M:%SZ') for t in time_list]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 07:30:05