如何在需要转换为JSON的Python对象中存储和访问日期时间?

0 投票
1 回答
4465 浏览
提问于 2025-04-17 18:08

我正在写我的第一个Python脚本,这个脚本可以创建和更新一个包含不同日期时间的对象。

我这样设置这个对象:

# Date conversion
import datetime
import time

# 0:01:00 and 0:00:00 threshold and totalseconds
threshold = time.strptime('00:01:00,000'.split(',')[0],'%H:%M:%S')
tick = datetime.timedelta(hours=threshold.tm_hour,minutes=threshold.tm_min,seconds=threshold.tm_sec).total_seconds()
zero_time = datetime.timedelta(hours=0,minutes=0,seconds=0)
zero_tick = zero_time.total_seconds()
format_date = '%d/%b/%Y:%H:%M:%S'

from datetime import datetime

# Response object
class ResponseObject(object):
    def __init__(self, dict):
      self.__dict__ = dict

# JSON encoding
from json import JSONEncoder
class MyEncoder(JSONEncoder):
    def default(self, o):
      return o.__dict__

# > check for JSON response object
try:
   obj
except NameError:
    obj = ResponseObject({})

...
entry = "14/Nov/2012:09:32:31 +0100"
entry_tz = str.join(' ', entry.split(None)[1:6])
entry_notz = entry.replace(' '+entry_tz,'')
this_time = datetime.strptime(entry_notz, format_date)

# > add machine to object if not there, add init time
if not hasattr(obj, "SOFTINST"):
    #line-breaks for readability
    setattr(obj, "SOFTINST", {  
        "init":this_time,
        "last":this_time,
        "downtime":zero_time,
        "totaltime":"",
        "percentile":100
    })
... 
print this_time
print MyEncoder().encode({"hello":"bar"})
print getattr(obj, "SOFTINST")

我最后的'print'输出是这样的:

{
  'totaltime': datetime.timedelta(0),
  'uptime': '',
  'last': datetime.datetime(2012, 11, 14, 9, 32, 31),
  'init': datetime.datetime(2012, 11, 14, 9, 32, 31),
  'percentile': 100, 
  'downtime': 0
}

但是我无法把它转换成JSON格式...

我不明白为什么会这样:

print this_time   #2012-11-14 09:32:31

但在这个对象里面,它是以

datetime.datetime(2012, 11, 14, 9, 32, 31)

问题:
我该如何把日期时间对象存储为“字符串格式”,同时又能在Python中方便地访问和修改它们呢?

谢谢!

1 个回答

2

在日期时间对象上使用isoformat方法。 (参考链接:http://docs.python.org/release/2.5.2/lib/datetime-datetime.html

撰写回答