如何将日期时间转换为字符串以插入 xml 标记(python、xml 和 psql)?

How can I transform a datetime into a string to insert in xml tag (python, xml and psql)?

我正在 python2 中开发一个脚本来生成一个 xml 文件,其中包含数据库(psql 数据库)中的信息,但我收到以下错误:

Cannot serialize datetime.datetime(2018, 2, 4, 23, 5) (type datetime)

代码如下:

for row in rows:
    Jobs = ET.SubElement(JobList, 'Jobs')
    ........
    scheduledTime.text = row[7]
    startTime.text = row[8]
    endTime.text = row[9]
    ........
    myJobList = ET.tostring(JobList)

查询的fetchall返回的数据为:

(3090, 'Backup-Local.2018-02-04_23.05.00_57', 'Backup-Local',
 'B', 'F', 1, 'T', datetime.datetime(2018, 2, 4, 23, 5),
 datetime.datetime(2018, 2, 4, 23, 5, 2), 
 datetime.datetime(2018, 2, 4, 23, 5, 20), 
 datetime.datetime(2018, 2, 4, 23, 5, 20), 
 1517785520L, 349, 1515088289, 488, 386893432L, 
 397505297L, 0, 0, 2, 16, 0, 0, 0, 0, 0, '', 'File')

我想知道如何 'translate' 返回字符串的日期时间或者 xml 中是否存在日期时间类型?!?!

在 google 搜索你的错误消息时,我发现了这个 post:

How to overcome "datetime.datetime not JSON serializable"?

推荐使用函数isoformat()进行转换。但是还有一个值得一读的更深入的讨论。

您可以使用 datetime 模块 strftime 方法将日期时间对象转换为字符串对象。

例如:

import datetime
s = (3090, 'Backup-Local.2018-02-04_23.05.00_57', 'Backup-Local',
 'B', 'F', 1, 'T', datetime.datetime(2018, 2, 4, 23, 5),
 datetime.datetime(2018, 2, 4, 23, 5, 2), 
 datetime.datetime(2018, 2, 4, 23, 5, 20), 
 datetime.datetime(2018, 2, 4, 23, 5, 20), 
 1517785520L, 349, 1515088289, 488, 386893432L, 
 397505297L, 0, 0, 2, 16, 0, 0, 0, 0, 0, '', 'File')

res = []
for i in s:
    if isinstance(i, datetime.datetime):
        res.append(i.strftime("%Y-%m-%d %H:%M:%S"))    #Convert datetime to string.
    else:
        res.append(i) 

print(res)
print(tuple(res))

输出:

[3090, 'Backup-Local.2018-02-04_23.05.00_57', 'Backup-Local', 'B', 'F', 1, 'T', '2018-02-04 23:05:00', '2018-02-04 23:05:02', '2018-02-04 23:05:20', '2018-02-04 23:05:20', 1517785520L, 349, 1515088289, 488, 386893432L, 397505297L, 0, 0, 2, 16, 0, 0, 0, 0, 0, '', 'File']

(3090, 'Backup-Local.2018-02-04_23.05.00_57', 'Backup-Local', 'B', 'F', 1, 'T', '2018-02-04 23:05:00', '2018-02-04 23:05:02', '2018-02-04 23:05:20', '2018-02-04 23:05:20', 1517785520L, 349, 1515088289, 488, 386893432L, 397505297L, 0, 0, 2, 16, 0, 0, 0, 0, 0, '', 'File')