简体   繁体   English

在 Python 中的 pandas 数据框的时间戳列中查找日期时间

[英]Find datetime in timestamp column of pandas dataframe in Python

I have a timestamp, say 1611903555682, which I convert into a datetime, ie 2021-01-29 07:59:15, and I want to find out whether this datetime is stored in a timestamp column of a pandas dataframe, which looks like:我有一个时间戳,比如 1611903555682,我将其转换为日期时间,即 2021-01-29 07:59:15,我想知道这个日期时间是否存储在 pandas 数据帧的时间戳列中,看起来像:

['2021-05-10T19:53:38.205000000' '2021-05-10T19:53:39.210000000' '2021-05-10T19:53:40.215000000' ... '2021-02-08T11:36:08.639000000' '2021-02-08T11:36:09.644000000' '2021-02-08T11:36:10.649000000'] ['2021-05-10T19:53:38.205000000' '2021-05-10T19:53:39.210000000' '2021-05-10T19:53:40.215000000' ... '2021-02-08T11:36:08.63910000002 -02-08T11:36:09.644000000''2021-02-08T11:36:10.649000000']

I want the comparison to look only at YYYY-MM-DD HH-MM-SS, so ignoring the milliseconds.我希望比较只看 YYYY-MM-DD HH-MM-SS,所以忽略毫秒。

I tried with the following我尝试了以下

 if pd.Timestamp(datetime.fromtimestamp(last_timestamp/1000).strftime("%Y-%m-%d, %H:%M:%S") ) in df_processed_timestamps['time'].values:
        print('Value is already in dataframe.')
        return

But this condition is never entered, even if values are actually in the dataframe (I checked it by printing the dataframe).但是这个条件永远不会被输入,即使值实际上在数据框中(我通过打印数据框来检查它)。 Am I doing a conversion error?我在做转换错误吗? In fact, if I run:事实上,如果我运行:

print(str(pd.Timestamp(datetime.fromtimestamp(last_timestamp/1000).strftime("%Y-%m-%d, %H:%M:%S") )))
     
print(df_processed_timestamps['time'].values)

I get:我得到:

 2021-01-29 07:59:15
['2021-05-10T19:53:38.205000000' '2021-05-10T19:53:39.210000000'
 '2021-05-10T19:53:40.215000000' ... '2021-02-08T11:36:08.639000000'
 '2021-02-08T11:36:09.644000000' '2021-02-08T11:36:10.649000000']

Any suggestion?有什么建议吗? Thanks!谢谢!

Your problem is that you convert timestamp to %Y-%m-%d, %H:%M:%S but values in time column is not that format.您的问题是您将timestamp转换为%Y-%m-%d, %H:%M:%Stime列中的值不是那种格式。

You can convert the time column to seconds then check if timestamp is in column您可以将time列转换为秒,然后检查timestamp是否在列中

timestamp = 1611903555682
isin = timestamp in pd.to_datetime(df['time']).values.astype(np.int64) // (10**6)
print(pd.to_datetime(df['time']).values.astype(np.int64) // (10**6))

[1620676418205 1620676419210 1620676420215 1612784168639 1612784169644
 1612784170649]

print(isin)

False

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

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