0

I'm developing a script in python2 to generate a xml file with information that is in a database (psql database), but I get the following error:

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

The code is the following:

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)

and the data returned by the fetchall of the query is:

(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')

I want to know how can I 'translate' the datetime returned to a string or if exists a datetime type in xml?!?!

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Micolho
  • 281
  • 2
  • 20
  • Did you try this https://stackoverflow.com/questions/10624937/convert-datetime-object-to-a-string-of-date-only-in-python – Sumit Jha Mar 20 '18 at 10:29
  • Sumit jha, i tried to search and didn't find anything... only json datetime erros... but ty :D – Micolho Mar 20 '18 at 10:35

2 Answers2

2

You can use the datetime modules strftime method to convert datetime object to string object.

Ex:

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))

Output:

[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')
Rakesh
  • 81,458
  • 17
  • 76
  • 113
1

When searching for ur error message at google i find this post:

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

there one is recommended to use function isoformat()for convertion. But there is a bright further discussion worth to be read.