As part of an XML-file I would like to have the following format of timestamp-string:
<time_stamp>20170120 14:38</time_stamp>
In the python-script to generate this XML-file (as well as an equivalent JSON-file), the following 2 instructions get & print the info for date&time:
now = datetime.datetime.now()
print 'Present Date & Time = ', now
The result of the print-line is like:
Present Date & Time = 2017-04-07 18:19:35.538690
As explained below the question, the first scriptline now=datetime.datetime.now() is apparently not suitable to get well-formatted info for the desired XML-line and for it's equivalent JSON-line.
Question: what is better replacement scriptline?
To put the timestamp-info into the JSON-dictionary and to print the result, I have following 2 script-lines:
DDS238_dict['time_stamp'] = now
print(DDS238_dict)
For that timestamp the printline has output like:
'time_stamp': datetime.datetime(2017, 4, 7, 18, 19, 35, 538690)
Generation of the json-file and xml-file is by the following 9 lines in the python-script:
# Make JSON-file
with open('DDS238_dict.json', 'w') as outfile:
json.dump(DDS238_dict, outfile)
# Convert dictionary to XML-file & print
DDS238_xml = dicttoxml.dicttoxml(DDS238_dict, attr_type=False)
print(DDS238_xml)
xml_output = open("DDS238_status.xml",'w')
xml_output.write(DDS238_xml)
xml_output.close()
For the generation of the JSON-file I get the following error-report:
TypeError: datetime.datetime(2017, 4, 7, 18, 19, 35, 538690) is not JSON serializable
From the generation of the XML-file I get the following result for the timestamp-string:
<time_stamp>2017-04-07T18:31:14.664248</time_stamp>
Answer:
Helped by the hints a link in StackOverflow [ How to print date in a regular format in Python? ] guided to a working solution:
=> add one extra scriptline for correct formatting of date&time, before putting the timestamp-info into the json-dictionary
dattim = datetime.datetime.now().strftime('%Y%m%d %H:%M')
DDS238_dict['time_stamp'] = dattim
print(DDS238_dict)