在使用json.dump时附加日期和时间戳?

时间:2019-06-26 07:18:17

标签: python json python-3.x logging

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

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,我想知道是否有一种方法可以将时间戳添加到日志中?例如20190607T220005 YearMonthDayTimeinHoursMinutesSeconds ??

2 个答案:

答案 0 :(得分:0)

如果您希望使用<DatePicker x:Name="Dp_DataFim" SelectedDate="{Binding MyProp}"> <DatePicker.Resources> <local:StringToDateTimeConverter x:Key="StringToDateTimeConverter" /> <Style TargetType="{x:Type DatePickerTextBox}"> <Setter Property="Template"> <Setter.Value> <ControlTemplate> <TextBox x:Name="PART_TextBox" Text="{Binding Path=SelectedDate, RelativeSource={RelativeSource AncestorType={x:Type DatePicker}}, Converter={StaticResource StringToDateTimeConverter}}" /> </ControlTemplate> </Setter.Value> </Setter> </Style> </DatePicker.Resources> </DatePicker> 格式的输出.json文件,则可以使用:

frame_ 20190607T220005_keypoints

如果要保留帧号:

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)

答案 1 :(得分:0)

我的答案假设您要为“ 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}