title: Comparing timestamps in dataframe columns with pandas
body: <p>Lets say I have a dataframe like this</p>
  <p>df1:</p>
  <pre><code>         datetime1                datetime2             
  0   2021-05-09 19:52:14      2021-05-09 20:52:14  
  1   2021-05-09 19:52:14      2021-05-09 21:52:14 
  2           NaN                      NaN
  3  2021-05-09 16:30:14               NaN
  4           NaN                      NaN
  5  2021-05-09 12:30:14        2021-05-09 14:30:14
  </code></pre>
  <p>I want to compare the timestamps in datetime1 and datetime2 and create a new column with the difference between them.</p>
  <p>In some scenarios I have a cases that I don't have values in datetime1 and datetime2, or I have values in datatime1 but I don't in datatime2, so is there is a possible way to get NaN in &quot;difference&quot; column if there is no timestamp in datetime1 and 2, and if there is a timestamp only in datetime1, get the difference compared to datetime.now() and put that in another column.</p>
  <p>Desirable df output:</p>
  <pre><code>         datetime1             datetime2          Difference in H:m:s    Compared with datetime.now()
  0   2021-05-09 19:52:14     2021-05-09 20:52:14       01:00:00                 NaN
  1   2021-05-09 19:52:14     2021-05-09 21:52:14       02:00:00                 NaN
  2           NaN                    NaN                  NaN                    NaN
  3   2021-05-09 16:30:14            NaN                  NaN                e.g(04:00:00)
  4           NaN                    NaN                  NaN                    NaN
  5  2021-05-09 12:30:14    2021-05-09 14:30:14         02:00:00                 NaN
  </code></pre>
  <p>I tried a solution from  @AndrejKesely, but it is failing if there is no timestamp in datetime1 and datetime2:</p>
  <pre><code>def strfdelta(tdelta, fmt):
      d = {&quot;days&quot;: tdelta.days}
      d[&quot;hours&quot;], rem = divmod(tdelta.seconds, 3600)
      d[&quot;minutes&quot;], d[&quot;seconds&quot;] = divmod(rem, 60)
      return fmt.format(**d)
  
  
  # if datetime1/datetime2 aren't already datetime, apply `.to_datetime()`:
  df[&quot;datetime1&quot;] = pd.to_datetime(df[&quot;datetime1&quot;])
  df[&quot;datetime2&quot;] = pd.to_datetime(df[&quot;datetime2&quot;])
  
  df[&quot;Difference in H:m:s&quot;] = df.apply(
      lambda x: strfdelta(
          x[&quot;datetime2&quot;] - x[&quot;datetime1&quot;],
          &quot;{hours:02d}:{minutes:02d}:{seconds:02d}&quot;,
      ),
      axis=1,
  )
  print(df)
  </code></pre>