繁体   English   中英

如何计算两个日期格式 Y/M/D h:m:s.ns 之间的差异

[英]How can I calculate the difference between two dates format Y/M/D h:m:s.ns

我需要减去两个日期,格式为 YMD hh:mm:ss,但我一直未能得到结果,尽管我找到了许多接近我的任务的解决方案。 这是我到目前为止得到的:

import pandas as pd

df = pd.read_excel('file.xlsx',header=0)
df['Time'] = pd.to_datetime(df['Time'])
df['Time']

import datetime as dt

df['Time'] = df['Time'].apply(lambda x: dt.datetime.strftime(x, '%Y-%m-%d %H:%M:%S'))
df['Time']
#print(df['Time'])
s1 = df['Time'].head(1)
print(s1)
s2=df.iloc[-1,2]
print(s2)

format = '%Y-%m-%d %H:%M:%S'
startDateTime = dt.datetime.strptime(s1, format)
endDateTime = dt.datetime.strptime(s2, format)

diff = endDateTime - startDateTime

我试过 pd.to_datetime 来转换它,但我仍然收到这个错误:

TypeError: strptime() argument 1 must be str, not Series

你能帮我解决这个问题吗? 谢谢!

如果将列转换为日期时间,则不需要其他对话,只需选择要标量的值并减去:

df['Time'] = pd.to_datetime(df['Time'])

startDateTime= df['Time'].iloc[0]
print(startDateTime)

#if 3rd column is filled by datetimes
endDateTime=df.iloc[-1,2]
print(endDateTime)

看起来您正在尝试使用 head() 函数检索 df['Time'] 系列的第一个元素,但该函数不起作用。 尝试:s1 = df['时间'][0]。

本质上,您将 Pandas 系列 (s1) 传递到需要字符串的 strptime 函数中。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM