【问题标题】:Appending date and time stamp while using json.dump?使用 json.dump 时附加日期和时间戳?
【发布时间】:2019-11-08 01:44:45
【问题描述】:

您好,我目前正在以下列方式转储每帧图像矩阵的输出。我

with open(os.path.join('logs', 'frame_{0}_keypoints.json'.format(str(frame_number).zfill(12))).format(frame_dict), 'w') as outfile:
   json.dump(my_dict, outfile)

有了这个,我可以得到 json 每帧文件,格式为 frame_000000000001_keypoints ,我想知道是否有办法将时间戳附加到日志?比如20190607T220005YearMonthDayTimeinHoursMinutesSeconds??

【问题讨论】:

  • 哪些日志?时间戳与图像处理有什么关系(给定标签)?
  • import time; time.asctime() 添加到您的字典中。
  • 你的意思是我应该附加它吗?
  • @timtensor 是否要向my_dict 添加新属性?时间戳?
  • 不是my_dict,而是每帧输出的文件名。文件名的命名

标签: python json python-3.x logging


【解决方案1】:

我的回答假设您想为“my_dict”添加时间戳。

import json
import time


class TimeStampAdderEncoder(json.JSONEncoder):
    def encode(self, obj):
        obj['timestamp'] = time.time()
        return json.JSONEncoder().encode(obj)


my_dict = {'key': 3}
my_dict_as_str = json.dumps(my_dict, cls=TimeStampAdderEncoder)
print(my_dict_as_str)

输出

{"key": 3, "timestamp": 1561542873.109698}

【讨论】:

    【解决方案2】:

    如果您希望输出具有此格式frame_ 20190607T220005_keypoints 的 .json 文件,您可以使用:

    import datetime 
    now = datetime.datetime.now()   
    
    now_isoFormat = now.isoformat() # GET - 2019-06-26T09:20:30.943730
    
    now_custom_isoFormat = "{YEAR}{MONTH}{DAY}T{HOUR}{MINUTES}{SECONDS}".format(
        YEAR=now.year,
        MONTH=now.month,
        DAY=now.day,
        HOUR=now.hour,
        MINUTES=now.minute,
        SECONDS=now.second) # GET - 2019626T092030
    
    with open(os.path.join('logs', 'frame_{0}_keypoints.json'.format(now_custom_isoFormat)).format(frame_dict), 'w') as outfile:
           json.dump(my_dict, outfile)
    

    如果您希望保留帧号:

    with open(os.path.join('logs', 'frame_{date}_keypoints_{frame}.json'
            .format(date=now_custom_isoFormat,
                    frame=str(frame_number).zfill(12)))
                      .format(frame_dict), 'w') as outfile:
        json.dump(my_dict, outfile)
    

    【讨论】:

    • 谢谢!是否可以附加帧号?然后我可以有frame_ 20190607T220005_keypoints_(per_frame) 的格式。我是从frame_{0}_keypoints.json'.format(str(frame_number).zfill(12))).format(frame_dict) 做的
    • 谢谢!这就是我想要的
    • 嗨弗兰克,我会将问题标签更改为已解决
    猜你喜欢
    • 1970-01-01
    • 2013-06-16
    • 2021-08-26
    • 2013-07-28
    • 2013-11-03
    • 2010-10-31
    • 2012-04-15
    • 2022-01-19
    • 2023-03-31
    相关资源
    最近更新 更多