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

Pandas中Datetime值异常:调用second属性返回0的问题

问题解决:datetime对象second返回值异常及Pandas Datetime显示错误

错误原因

你在创建datetime对象时搞错了构造函数的参数顺序。datetime(year, month, day, hour=0, minute=0, second=0, ...)的参数中,第四个是hour,第五个是minute,第六个才是second。你直接在hour之后传入sec_=15,相当于把15赋值给了minute参数,而second使用了默认值0,所以调用time_.second会返回0。

修复方法

有两种方式可以修正这个问题:

  1. 按参数顺序补全minute参数(如果你的minute为0):
import numpy as np 
import pandas as pd 
from datetime import datetime 

year_= 2019
month_= 8
day_= 7
hour_= 6
sec_= 15

# 补全minute参数(设为0)后传入second
time_= datetime(year_, month_, day_, hour_, 0, sec_)
print(time_.second)  # 输出15
  1. 使用关键字参数指定second,避免顺序混淆(推荐这种方式,可读性更强):
time_= datetime(year_, month_, day_, hour_, second=sec_)
print(time_.second)  # 输出15

Pandas Datetime问题关联修复

如果Pandas中的Datetime显示错误是因为使用了错误的datetime对象导致的,修复上述datetime对象的创建方式后,将正确的time_传入Pandas(比如pd.Series([time_])),就能正常显示Datetime值了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 14:06:25