gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 04:03:13 24 4
gpt4 key购买 nike

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

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

最佳答案

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

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)

关于python - 如何计算两个日期格式 Y/M/D h :m:s. ns 之间的差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57821497/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com