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

时间:2019-09-06 11:52:32

标签: python pandas datetime

我需要减去两个日期,格式为Y-M-D 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

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

2 个答案:

答案 0 :(得分:1)

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

counts

答案 1 :(得分:0)

好像您正在尝试使用无法正常使用的head()函数检索df ['Time']系列的第一个元素。试试:s1 = df ['时间'] [0]。

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