【发布时间】:2022-02-01 01:20:10
【问题描述】:
我正在创建多个以时间戳命名的 JSON 文件:
# open file for writing, "w"
now = datetime.now()
timestr = now.strftime("%Y%m%d-%H%M%S")
res['Date'] = timestr
file = ujson.dumps(res)
f = open(timestr+".json","w")
# write json object to file
f.write(file)
# close file
f.close()
生成如下所示的文件:
20220131-161407.json
我现在只想读取过去 90 分钟内创建的文件,因此我已经生成了相关的时间戳:
d = datetime.now() - timedelta(hours=1, minutes=30)
d.strftime("%Y%m%d-%H%M%S")
如何只读取带有相关时间戳的 JSON 文件?我现在使用以下内容读取目录中的所有文件:
json_files = [pos_json for pos_json in os.listdir(cwd) if pos_json.endswith('.json')]
dfs = [] # an empty list to store the data frames
for file in json_files:
data = pd.read_json(file, lines=True) # read data frame from json file
dfs.append(data) # append the data frame to the list
temp = pd.concat(dfs, ignore_index=True) # concatenate all the data frames in the list.
而且加载需要很长时间。
【问题讨论】:
-
为什么不从
pos_json字符串中解析时间戳,并在列表推导中添加除endswith('.json')之外的另一个条件(即解析时间大于d)? -
我试图这样做,但我错过了一些东西:
json_files = [pos_json for pos_json in os.listdir(cwd) if pos_json.endswith('.json') & pos_json> d ]。得到一个错误 unsupported operand type(s) for &: 'bool' and 'str' -
逻辑“与”运算符在 Python 中称为
and,而不是&。而且您没有从pos_json解析日期时间(您可能会比较字符串表示形式,但您需要在比较之前将d格式化为字符串)。 -
使用
with语句而不是显式的打开/关闭,因为它更像pythonic -
从技术上讲,您也不需要文件名中的 itmestamp。您可以执行
os.listdir之类的操作并获取每个文件的最后创建/修改日期,然后按该日期值对其进行排序或过滤。