【发布时间】:2022-01-12 10:41:01
【问题描述】:
我有一个每分钟一行的数据框。我需要访问当前分钟对应的行
value
2022-01-12 11:27:24+01:00 a
2022-01-12 11:28:41+01:00 b
2022-01-12 11:29:36+01:00 c
2022-01-12 11:30:11+01:00 d
2022-01-12 11:31:03+01:00 e
2022-01-12 11:32:39+01:00 f
我必须马上匹配。我尝试使用pandas 和datetime(重现它的代码)找到当前时间:
import pandas as pd
import numpy as np
import string
import datetime
start_idx=(datetime.datetime.now()).strftime(format="%Y-%m-%d %H:%M")
end_idx=(datetime.datetime.now()+datetime.timedelta(minutes=+5)).strftime(format="%Y-%m-%d %H:%M")
index_today = pd.date_range(start=start_idx, end=end_idx, freq='1T',tz='Europe/Rome')
# create random seconds
index_today=[i+ pd.DateOffset(seconds=np.random.randint(0,59)) for i in index_today]
df = pd.DataFrame(index=index_today, data=list(string.ascii_lowercase[0:len(index_today)]),columns=['value'])
now_pandas = pd.to_datetime("now").round(freq='min').tz_localize('utc').tz_convert('Europe/Rome')
now_datetime = datetime.datetime.now().strftime(format="%Y-%m-%d %H:%M")
out_pandas=df.loc[df.index.floor('Min')==now_pandas, :]
out_datetime=df.loc[now_datetime, :]
print('now pandas is ',now_pandas)
print('now datetime is ',now_datetime)
print('Current value found with Pandas:\n',out_pandas)
print('Current value found with datetime\n',out_datetime)
但有时它们会给出不同的结果:
now pandas is 2022-01-12 11:46:00+01:00
now datetime is 2022-01-12 11:45
Current value found with Pandas:
value
2022-01-12 11:46:08+01:00 b
Current value found with datetime
value
2022-01-12 11:45:35+01:00 a
最好和最可靠的方法是什么?
另外,我注意到如果数据帧不支持 tz,那么 pd.to_datetime("now") 会在 utc 中给出时间,我需要对其进行本地化、转换,然后将其转回 tz-naive。有什么解决办法吗?
非常感谢!!
【问题讨论】:
-
将随机数放入“可重现”的示例中看起来不是一个好主意。
-
所以你的问题是为什么结果不同? - 首先,确保构建用于比较的日期/时间;目前,
now_pandas被四舍五入到分钟,而now_datetime被剪裁到分钟。 -
感谢您的 cmets,Fuppes 先生,四舍五入和精确到分钟之间有什么区别?
-
四舍五入的意思是,例如,如果时间是 12:30:31,你得到 12:31。 Clipped 表示 12:30:31 => 12:30,即秒数只是“截断”。一般建议:如果在 pandas 中处理时间序列数据,您根本不需要 Python datetime。 pandas 内置插件在许多情况下提供了更多选项,并且可以与其他 pandas 功能很好地协同工作。
-
好的,非常感谢,现在清楚多了。那么你能告诉我当前访问数据框的最佳方式是什么(然后使用 pandas)?
标签: python pandas datetime utc