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

如何避免转为字符串对象,修改时间格式或修正无效时间值?

不转换为字符串的datetime时间处理方案

一、修正CSV时间列的秒数为00(保持datetime类型)

如果CSV的时间列已经解析为datetime对象,直接修改秒字段即可,全程无需转字符串:

import pandas as pd

# 假设df是读取的CSV数据,time_col为目标时间列
# 方法1:直接替换秒数
df['time_col'] = df['time_col'].apply(lambda dt: dt.replace(second=0))
# 方法2:用pandas dt属性高效取整到分钟(自动把秒设为00)
df['time_col'] = df['time_col'].dt.floor('min')

如果CSV还未解析为datetime类型,先解析再处理:

# 先按原格式解析为datetime
df['time_col'] = pd.to_datetime(df['time_col'], format='%H:%M:%S')
# 再修正秒数
df['time_col'] = df['time_col'].dt.floor('min')

处理后列的类型仍为datetime64[ns],完全保留datetime类型特性。

二、实现12小时制展示(不转字符串)

datetime对象本身不存储显示格式,它仅封装时间戳数值。要在保持datetime类型的同时以%I:%M:%S %p格式展示,可从显示层入手:

自定义格式化函数

定义专用函数处理显示逻辑,不修改原datetime对象:

def to_12h_format(dt):
    hour_12 = dt.hour % 12
    # 处理0点转为12点的情况
    hour_12 = 12 if hour_12 == 0 else hour_12
    period = 'AM' if dt.hour < 12 else 'PM'
    return f"{hour_12}:{dt.minute:02d}:{dt.second:02d} {period}"

# 使用示例:打印某条记录的12小时制时间
print(to_12h_format(df['time_col'].iloc[0]))

Pandas全局显示设置

如果用Pandas处理数据,可直接设置全局日期显示格式,不改变数据类型:

pd.options.display.date_format = '%I:%M:%S %p'
# 此时打印DataFrame,时间列会自动以12小时制展示,但底层仍为datetime类型

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 15:15:10