I am using objectmapper.enable(SerializationFeature.INDENT_OUTPUT).writerWithDefaultPrettyPrinter().writeValueAsString(r);
Result: "begin" : 1513644267698,
which returns the values in the object 'r' and the time in epoch format as stored. I now wish to print the time in a readable format, so i did the following change:
DateFormat df = new SimpleDateFormat(dateFormat);
return myMapper.setDateFormat(df).enable(SerializationFeature.INDENT_OUTPUT).writerWithDefaultPrettyPrinter().writeValueAsString(r);
Here i can pass the required dateFormat and print it in my desired format for eg. "EEE MMM dd, yyyy HH:mm:ss.SSS (z)".
Result: "begin" : "Tue Feb 20, 2018 09:02:24.941 (UTC)",
My question is - is there any way where i can print both epoch time and the above time format together in the same.
Required Result: "updatedTime" : [1513644267698] Tue Feb 20, 2018 09:02:24.941 (UTC),
Related
Error:
send: b'{"specversion": "1.0", "logEntryBatches": [{"entries": [{"data": "{\\"hello\\": \\"oracle\\", \\"as\\": \\"aaa\\"}", "id": "ocid1.test.oc1..jkhjkhh23423fd", "time": "2021-04-01T12:19:28.416000Z"}], "source": "EXAMPLE-source-Value", "type": "remediationLogs", "defaultlogentrytime": "2021-04-01T12:19:28.416000Z"}]}'
reply: 'HTTP/1.1 400 Bad Request\r\n'
header: Date: Fri, 02 Apr 2021 07:39:16 GMT
header: opc-request-id: ER6S6HDVTNWUOKCJ7XXZ/OpcRequestIdExample/770899C2C7CA6ABA11D996CC57E8EE8F
header: Content-Type: application/json
header: Connection: close
header: Content-Length: 79
Traceback (most recent call last):
File "tool.py", line 45, in <module>
put_logs_response = loggingingestion_client.put_logs(
File "/home/ubuntu/.local/lib/python3.8/site-packages/oci/loggingingestion/logging_client.py", line 172, in put_logs
return self.base_client.call_api(
File "/home/ubuntu/.local/lib/python3.8/site-packages/oci/base_client.py", line 276, in call_api
response = self.request(request)
File "/home/ubuntu/.local/lib/python3.8/site-packages/oci/base_client.py", line 388, in request
self.raise_service_error(request, response)
File "/home/ubuntu/.local/lib/python3.8/site-packages/oci/base_client.py", line 553, in raise_service_error
raise exceptions.ServiceError(
oci.exceptions.ServiceError: {'opc-request-id': 'ER6S6HDVTNWUOKCJ7XXZ/OpcRequestIdExample/770899C2C7CA6ABA11D996CC57E8EE8F', 'code': 'InvalidParameter', 'message': 'Unable to process JSON input', 'status': 400}
I am trying to send json data to Oracle logs, but getting the above error. I am using json.dumps(data) to convert the dict to string. Kindly let me know if any workaround available to this.
Code:
data = {'hello':'oracle', "as":"aaa"}
put_logs_response = loggingingestion_client.put_logs(
log_id="ocid1.log.oc1.iad.<<Log OCID>>",
put_logs_details=oci.loggingingestion.models.PutLogsDetails(
specversion="1.0",
log_entry_batches=[
oci.loggingingestion.models.LogEntryBatch(
entries=[
oci.loggingingestion.models.LogEntry(
data= json.dumps(data),
id="ocid1.test.oc1..jkhjkhh23423fd",
time=datetime.strptime(
"2021-04-01T12:19:28.416Z",
"%Y-%m-%dT%H:%M:%S.%fZ"))],
source="EXAMPLE-source-Value",
type="Logs",
defaultlogentrytime=datetime.strptime(
"2021-04-01T12:19:28.416Z",
"%Y-%m-%dT%H:%M:%S.%fZ"))]),
timestamp_opc_agent_processing=datetime.strptime(
"2021-04-01T12:19:28.416Z",
"%Y-%m-%dT%H:%M:%S.%fZ"),
opc_agent_version="EXAMPLE-opcAgentVersion-Value",
opc_request_id="ER6S6HDVTNWUOKCJ7XXZ/OpcRequestIdExample/")
This exception indicates that you have an InvalidParameter in your JSON input.
oci.exceptions.ServiceError: {'opc-request-id': 'ER6S6HDVTNWUOKCJ7XXZ/OpcRequestIdExample/770899C2C7CA6ABA11D996CC57E8EE8F', 'code': 'InvalidParameter', 'message': 'Unable to process JSON input', 'status': 400}
The InvalidParameter is your timestamp, which is date - 2021-04-01T12:19:28.416Z.
According to Oracle's documentation you need to use a RFC3339-formatted date-time string with milliseconds precision when creating a LogEntry.
This code snippet is from oci-python-sdk - log_entry.py, but it doesn't mention the milliseconds precision like Oracle's documentation.
#time.setter
def time(self, time):
"""
Sets the time of this LogEntry.
Optional. The timestamp associated with the log entry. An RFC3339-formatted date-time string.
If unspecified, defaults to PutLogsDetails.defaultlogentrytime.
:param time: The time of this LogEntry.
:type: datetime
"""
self._time = time
This code create a UTC RFC3339 complaint timestamp with milliseconds precision
from datetime import datetime
from datetime import timezone
current_utc_time_with_offset = datetime.now(timezone.utc).isoformat()
print(current_utc_time_with_offset)
#output
2021-04-06T13:00:52.706040+00:00
current_utc_time_with_timezone = datetime.now(timezone.utc).isoformat().replace("+00:00", "Z")
print(current_utc_time_with_timezone)
#output
2021-04-06T13:09:10.053432Z
This Stack Overflow question is worth a read:
What's the difference between ISO 8601 and RFC 3339 Date Formats?
This article is also useful:
Understanding about RFC 3339 for Datetime and Timezone Formatting in Software Engineering
Your data looks fine , I think the issue is that Time precision is more than millisec. it should work fine if you loose the trailing zeros in time.
Format a datetime into a string with milliseconds
https://docs.oracle.com/en-us/iaas/api/#/en/logging-dataplane/20200831/LogEntry/
Your time is RFC3339 but precision is more than millisec
'{"specversion": "1.0", "logEntryBatches": [{"entries": [{"data": "{\"hello\": \"oracle\", \"as\": \"aaa\"}", "id": "ocid1.test.oc1..jkhjkhh23423fd", "time": "2021-04-01T12:19:28.416000Z"}], "source": "EXAMPLE-source-Value", "type": "remediationLogs", "defaultlogentrytime": "2021-04-01T12:19:28.416000Z"}]}'
See https://docs.oracle.com/en-us/iaas/api/#/en/logging-dataplane/20200831/LogEntry/
The timestamp associated with the log entry. An RFC3339-formatted date-time string with milliseconds precision. If unspecified, defaults to PutLogsDetails.defaultlogentrytime.
I am working through w3schools, particularly https://www.w3schools.com/js/js_json_parse.asp
I ran this example and got an unexpected result
let dashText = '{ "name":"John", "birth":"1986-12-14", "city":"New York"}';
let objD = JSON.parse(dashText);
console.log("objD: ", objD);
objD.birth = new Date(objD.birth);
console.log("objD.birth: ", objD.birth);
3:09:04 PM Info objD: { name: 'John', birth: '1986-12-14', city: 'New York' }
3:09:04 PM Info objD.birth: Sat Dec 13 1986 18:00:00 GMT-0600 (Central Standard Time)
Note the difference in the dates. I then changed the dashes to slashes out of curiosity and the date was correctly determined from the string.
let slashText = '{ "name":"John", "birth":"1986/12/14", "city":"New York"}';
let objS = JSON.parse(slashText);
console.log("objS: ", objS);
objS.birth = new Date(objS.birth);
console.log("objS.birth: ", objS.birth);
3:09:04 PM Info objS: { name: 'John', birth: '1986/12/14', city: 'New York' }
3:09:04 PM Info objS.birth: Sun Dec 14 1986 00:00:00 GMT-0600 (Central Standard Time)
Can anyone explain the results?
Javascript parses DateTime strings differently based on how the string is formatted. The dashes are parsed to ISO date, i.e. international time. You can see this when it tries to handle the timezone conversion, where it sets the time to 18:00:00 to account for the 6 hour shift from Universal Time. Slashes are parsed as just the date, and doesn't try to adjust the time based on timezones.
Here's a w3schools link that goes over this in more detail.
Have a dates saved in my sqlite database in this format 2019-01-24 13:41:40.515955 and when I output to my web page its displayed as 2019-01-24 13:41:40 UTC. Please can I get guidance on displaying something like Wed 24 January 2019 ? No sure how to approach it
Use Javascript, would be a simple approach to parse and format dates with desired output.
var date = new Date('6/29/2011 4:52:48 PM UTC');
date.toString() // "Wed Jun 29 2011 09:52:48 GMT-0700 (PDT)"
var date = new Date('6/29/2011 4:52:48 PM UTC');
date.toString() // "Wed Jun 29 2011 09:52:48 GMT-0700 (PDT)"
console.log(`Year: ${date.getFullYear()}, Month: ${date.getMonth()}, Day, ${date.getDay()}`)
You can also parse dates using Date.parse(``);
I have a REST request that will return a json response with a set of nine keys and there values. No the input values for the request are randomized and therefore will I will get different values every time it is run.
Is is possible to create a script assertion that will just validated whether the json structure is correct.
Json Response:
{
"sid": 636811,
"poss": 122,
"mis": -150,
"pres": 253,
"aea": 0,
"aa": 12,
"ua": 7,
"lar": null,
"lbr": 1
}
Script Assertion:
def expectedMap = [sid:'', poss:'', mis:'', pres:'', aea:'', aa:'', ua:'', lar:'', lbr:'']
def json = new groovy.json.JsonSlurper().parseText(context.response))
assert json.keySet().sort() == expectedMap.keySet().sort()
I believe the following script assertion I have is failing because is it asserting the key values as well.
log.info expectedMap.keySet().sort()
log.info json.keySet().sort()
Tue Jun 26 14:27:52 BST 2018:INFO:[aa, aea, lar, lbr, mis, poss, pres, sid, ua]
Tue Jun 26 14:27:52 BST 2018:INFO:[aa, aea, lar, lbr, mis, poss, pres, sid, ua]
log.info expectedMap.keySet().sort().getClass()
log.info json.keySet().sort().getClass()
Tue Jun 26 14:17:12 BST 2018:INFO:class java.util.ArrayList
Tue Jun 26 14:17:12 BST 2018:INFO:class java.util.TreeMap$KeySet
You are almost there. Just need to get the keys, sort them and compare.
Change from:
assert expectedMap == json, 'Actual response is not matching with expected data'
To:
assert expectedMap.keySet().sort() == json.keySet().sort() as List, 'Actual response is not matching with expected data'
How to convert {7/4/2016 5:00:00 Am} to "July 4, 2016" in SQL. This has to be done in SQL only as I need to send the date as in {7/4/2016 5:00:00 Am} format and need to store and retrieve back in "July 4, 2016" format.
I am using SQL Server Management Studio 2012.
If SQL Server 2012+ you can use the format() function
select format(cast('7/4/2016 5:00:00 Am' as datetime),'MMMM d, yyyy')
Returns
July 4, 2016