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

如何使用pandas或字符串操作将Timestamp列转换为12小时制时间格式

Pandas时间字符串格式转换解决方案

你可以通过以下两种方法实现将Timestamp列的字符串(如353)转换为3:53 pm格式的需求:


方法1:使用pandas内置时间处理(推荐)

利用pandas的日期解析能力,代码更简洁,后续也可以方便地做其他时间运算:

import pandas as pd

# 你的原始DataFrame构造代码
c = pd.DataFrame({"Timestamp":x,"Latitude":y,"Longitude":z})

# 1. 给时间字符串补前导零,统一为4位长度(如"353" → "0353")
c['Timestamp'] = c['Timestamp'].str.zfill(4)
# 2. 解析为时间类型后格式化为12小时制带am/pm的格式
c['Formatted_Time'] = pd.to_datetime(c['Timestamp'], format='%H%M').dt.strftime('%-I:%M %p').str.lower()

参数说明:

  • %H%M:指定输入字符串为「24小时制小时+分钟」的格式
  • %-I:12小时制的小时,自动去掉前导零(Windows系统运行报错可替换为%#I)
  • %p:输出AM/PM标识,调用.str.lower()转为小写的am/pm

方法2:纯字符串自定义转换

不需要依赖pandas的时间解析逻辑,灵活度更高,可自定义适配特殊规则:

def convert_timestamp(time_str):
    # 补前导零到4位
    time_str = time_str.zfill(4)
    hour = int(time_str[:2])
    minute = time_str[2:]
    # 判断上午/下午
    period = "am" if hour < 12 else "pm"
    # 转换为12小时制
    hour_12 = hour % 12
    hour_12 = 12 if hour_12 == 0 else hour_12
    return f"{hour_12}:{minute} {period}"

c['Formatted_Time'] = c['Timestamp'].apply(convert_timestamp)

备注:如果你的原始Timestamp数值默认代表下午时间(例如353固定为下午3点而非凌晨3点),可在函数内增加判断:如果hour < 12则hour += 12,即可适配规则。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 06:54:00