使用datetime/str-python的两列之间的datetime差

b0zn9rqh  于 2021-08-20  发布在  Java
关注(0)|答案(2)|浏览(271)

我有一个数据集-在下面

Create              Complete
0   2005-01-02 01:15:00 2005-01-05 14:05:00
1   2005-01-06 00:00:00 open

我想用下面的代码得到两者之间的分钟差。但是,由于“complete”列也包含一个字符串值,我如何才能获得pandas到ign

df['diff_mins'] = df.Create - df.Complete
oalqel3c

oalqel3c1#

您可以使用pd.to_datetime,例如:

import pandas as pd

df = pd.DataFrame([
    ['2005-01-02 01:15:00', '2005-01-05 14:05:00'], 
    ['2005-01-06 00:00:00', 'open']],
    columns=('Create', 'Complete')
)

然后:

df['diff_mins'] = (
    pd.to_datetime(df.Create) - pd.to_datetime(df.Complete, errors='coerce')
)

给你:

print(df)
                Create             Complete         diff_mins
0  2005-01-02 01:15:00  2005-01-05 14:05:00 -4 days +11:10:00
1  2005-01-06 00:00:00                 open               NaT
dced5bon

dced5bon2#

我试着用 map . 它应该是这样的:

import datetime

def get_diff_mins(elem_a, elem_b):
  if (elem_b=='open'):
    elem_b = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
  a = elem_a.replace(' ', '-').replace(':','-').split('-')
  b = elem_b.replace(' ', '-').replace(':','-').split('-')
  # Roughly converts yearly time to mins
  # since month is always considered 30 days
  f = [60*24*30*12, 60*24*30, 60*24, 60, 1, 0]
  mins_a = sum([int(a)*f for a,f in zip(a,f)])
  mins_b = sum([int(b)*f for b,f in zip(b,f)])
  return mins_a-mins_b

df['diff_mins'] = map(get_diff_mins, df.Create, df.Complete)

相关问题