how to pass date in json data - python

import datetime
import json
def receive(self, event, **kwargs):
payload={
"id":event.id,
"lastReceiveTime":event.lastreceivetime
"createTime":event.createtime,
"receiveTime":event.receivetime
}
r = requests.post("http://localhost:8000/curlRequest", json=payload, headers=self.headers)
return event
i'm getting error Object of type datetime is not JSON serializable
i have tried "lastReceiveTime":datetime.event.lastreceivetime....but this has also not worked.

You could pass in the Unix time, and when you retrieve it in your application convert that to the format you prefer.
To get the Unix time in python:
import time
current_time = time.time()
current_time will be of type float.
In your case, you could also just convert the datetime object to a unix timestamp if you cannot control the type of event.createtime and event.recievetime.
The below code should do that:
import datetime
import time
import json
def receive(self, event, **kwargs):
last_time = event.lastrecievetime.timestamp()
create_time = event.createtime.timestamp()
recieve_time = event.recievetime.timestamp()
payload={
"id":event.id,
"lastReceiveTime":last_time
"createTime":create_time,
"receiveTime":receive_time
}
r = requests.post("http://localhost:8000/curlRequest", json=payload, headers=self.headers)
return event

Related

Python: determine current time is not older than 5 minutes

from API I get my latest event time, I want to check if my event time coming from the API is not older than 5 minutes, here is my code
import json
from typing import Optional
import datetime
import time
import requests
def check_event():
now = datetime.datetime.now()
old_time = datetime.datetime.now() - datetime.timedelta(minutes=5)
res = requests.post(URL, data=json.dumps(PAYLOAD), headers=headers)
available_event = res.json()
print(available_event[0]['result']['time'])
event_time = available_lag[0]['result']['time']
ev2 = datetime.datetime.strptime(event_time,'%Y-%m-%dT%H:%M:%S.%f%z' )
print(ev2)
if event_time < old_time:
print(" old")
else:
print("fresh")
from my API time returns in this formate
2022-04-14T07:28:08.000Z
and when I strip the event_time to convert str to datetime, I get following outout
2022-04-14 07:49:27+00:00
and print of the old_time varible format is following
2022-04-14 10:23:08.169712
and when I compare both times, I get following error
TypeError: '<' not supported between instances of 'str' and
'datetime.datetime'
how to fix this?
[Edited]. Yeah, as is stated bellow you can use timezone from datetime module:
from datetime import datetime, timedelta, timezone
def check_event(event_time):
event_time = datetime.strptime(event_time, '%Y-%m-%dT%H:%M:%S.%f%z')
return event_time > datetime.now(timezone.utc) - timedelta(minutes=5)
time_from_API = '2022-04-14T07:28:08.000Z'
print(check_event(time_from_API))

how to set timezone in local variable using python?

I was trying to read s3 file which is a fee summary report and now i am trying to Check if the report is present and if the report is older than specified time (configurable) and return boolean
my code is shown below,
import boto3
import json
import os
BUCKET_NAME = os.getenv('')
KEY = os.getenv('')
def send_notification():
report = get_report()
print(bool(report))
print(report)
def get_report():
s3_client = boto3.client('s3')
response = s3_client.get_object(Bucket=BUCKET_NAME, Key=KEY)
data = response['Body'].read()
report = json.loads(data)
return report
I need to set a time locally and compare it with the date which is there on the fee summary report and return a boolean value. Kindly looking for someone's help. Thanks in advance.
Let's say you have a column of dates. You can convert the time to your desired timezone, e.g. "America/Los_Angeles" using the datetime and pytz module.
import datetime as dt
import pytz
dates = ["2017-01-01 14:00:00","2017-01-01 14:00:00", "2017-01-01 14:00:00","2017-01-01 14:30:00"]
for d in dates:
start = dt.datetime.strptime(d, "%Y-%m-%d %H:%M:%S")
start = start.replace(tzinfo=pytz.utc)
local_tz = pytz.timezone("America/Los_Angeles") # convert to desired timezone
To check if a time is greater than any specific time, let's say 9 o'clock, use:
utc = pytz.utc
loc_dt = utc.localize(datetime.datetime.today().replace(hour=9, minute=0))
today = utc.localize(datetime.datetime.today())
if loc_dt < today:
print("True")

Flask loop takes long time to complete

I have this loop in my app.py. For some reason it extends the load time by over 3 seconds. Are there any solutions?
import dateutil.parser as dp
# Converts date from ISO-8601 string to formatted string and returns it
def dateConvert(date):
return dp.parse(date).strftime("%H:%M # %e/%b/%y")
def nameFromID(userID):
if userID is None:
return 'Unknown'
else:
response = requests.get("https://example2.org/" + str(userID), headers=headers)
return response.json()['firstName'] + ' ' + response.json()['lastName']
logs = []
response = requests.get("https://example.org", headers=headers)
for response in response.json():
logs.append([nameFromID(response['member']), dateConvert(response['createdAt'])])
It extends the load time by over 3 seconds because it does a lot of unnecessary work, that's why.
You're not using requests Sessions. Each request will require creating and tearing down an HTTPS connection. That's slow.
You're doing another HTTPS request for each name conversion. (See above.)
You're parsing the JSON you get in that function twice.
Whatever dp.parse() is (dateutil?), it's probably doing a lot of extra work parsing from a free-form string. If you know the input format, use strptime.
Here's a rework that should be significantly faster. Please see the TODO points first, of course.
Also, if you are at liberty to knowing the member id -> name mapping doesn't change, you can make name_cache a suitably named global variable too (but remember it may be persisted between requests).
import datetime
import requests
INPUT_DATE_FORMAT = "TODO_FILL_ME_IN" # TODO: FILL ME IN.
def dateConvert(date: str):
return datetime.datetime.strptime(date, INPUT_DATE_FORMAT).strftime(
"%H:%M # %e/%b/%y"
)
def nameFromID(sess: requests.Session, userID):
if userID is None:
return "Unknown"
response = sess.get(f"https://example2.org/{userID}")
response.raise_for_status()
data = response.json()
return "{firstName} {lastName}".format_map(data)
def do_thing():
headers = {} # TODO: fill me in
name_cache = {}
with requests.Session() as sess:
sess.headers.update(headers)
logs = []
response = sess.get("https://example.org")
for response in response.json():
member_id = response["member"]
name = name_cache.get(member_id)
if not name:
name = name_cache[member_id] = nameFromID(sess, member_id)
logs.append([name, dateConvert(response["createdAt"])])

Adding seconds to ISO 8601 datestamp string

I am trying to add seconds to a datestamp string that is received from a json object but the datetime function I am trying to use does not allow strings and wants the date to be separated like: datetime.strftime(2011,11,18). Here is what I have:
import requests
from datetime import datetime
def call():
pay = {'token' : "802ba928cd3ce9acd90595df2853ee2b"}
r = requests.post('http://challenge.code2040.org/api/dating',
params=pay)
response = r.json()
time = response['datestamp']
interval = response['interval']
utc = datetime.strftime(time, '%Y-%m-%dT&H:%M:%S.%fZ')
timestamp = (utc-time).total_seconds()
utc_dt = datetime(time) + timedelta(seconds=timestamp)
print(utc_dt.strftime('%Y-%m-%dT%H:%M:%S.%fZ'))
Is there another way I can add time to a ISO8601 datestamp?

Jira python calculate time

I am trying to calculate the time from the issue is created and until it is resolved. With these fields:
creation_time = issue.fields.created
resolved_time = issue.fields.resolutiondate
Output when I print:
Creation: 2016-06-09T14:37:05.000+0200 Resolved: 2016-06-10T10:53:12.000+0200
Is there anyway I can minus the resolution date and time with the creation date and time to find how much time is spent on a issue?
Parse the date/time strings into a suitable datetime object and then you can use those to do calculations.
This post explains how to parse a date/time string or you can just take a look at the documentation for the strptime() method.
For calculations, there are examples in this post and there's detailed documentation here.
As an example, something like this should be close to a solution:
from datetime import datetime
from datetime import timedelta
createdTime = datetime.strptime('2016-06-09T14:37:05.000+0200', '%Y-%m-%dT%H:%M:%S.%f')
resolvedTime = datetime.strptime('2016-06-10T10:53:12.000+0200', '%Y-%m-%dT%H:%M:%S.%f')
duration = resolvedTime - createdTime
duration will be a timedelta object and you can access duration.days, duration.seconds and duration.microseconds to get its info.
strptime does have as a drawback that it does not support parsing timezones, so you'll have to cut that part of your input first. Alternatively, see this post.
strptime does not support parsing timezones.
This code is working for me
from datetime import datetime
createdTime = datetime.strptime(issue.fields.created.split(".")[0], '%Y-%m-%dT%H:%M:%S')
resolvedTime = datetime.strptime(issue.fields.resolutiondate.split(".")[0], '%Y-%m-%dT%H:%M:%S')
duration = resolvedTime - createdTime
I've write a function which calculates mean, median and variance of the respond times in days. Hope that helps;
import datetime as d
import numpy as np
ymd_create = []
ymd_resdate = []
delta_t = []
class calculate:
def __init__(self):
self.result = 0
def meantime(self, issueobject):
for i in range(0, len(issueobject)):
ymd_create.append(d.datetime(int(issueobject[i].raw[u'fields'][u'created'].split('T')[0].split('-')[0]), int(issueobject[i].raw[u'fields'][u'created'].split('T')[0].split('-')[1]), int(issueobject[i].raw[u'fields']
[u'created'].split('T')[0].split('-')[2]), int(issueobject[i].raw[u'fields'][u'created'].split('T')[1].split(':')[0]), int(issueobject[i].raw[u'fields'][u'created'].split('T')[1].split(':')[1])))
ymd_resdate.append(d.datetime(int(issueobject[i].raw[u'fields'][u'resolutiondate'].split('T')[0].split('-')[0]), int(issueobject[i].raw[u'fields'][u'resolutiondate'].split('T')[0].split('-')[1]), int(issueobject[i].raw[u'fields']
[u'resolutiondate'].split('T')[0].split('-')[2]), int(issueobject[i].raw[u'fields'][u'resolutiondate'].split('T')[1].split(':')[0]), int(issueobject[i].raw[u'fields'][u'resolutiondate'].split('T')[1].split(':')[1])))
delta_t.append((ymd_resdate[i] - ymd_create[i]).days)
self.result = np.mean(np.array(delta_t))
return self.result
def mediantime(self, issueobject):
for i in range(0, len(issueobject)):
ymd_create.append(d.datetime(int(issueobject[i].raw[u'fields'][u'created'].split('T')[0].split('-')[0]), int(issueobject[i].raw[u'fields'][u'created'].split('T')[0].split('-')[1]), int(issueobject[i].raw[u'fields']
[u'created'].split('T')[0].split('-')[2]), int(issueobject[i].raw[u'fields'][u'created'].split('T')[1].split(':')[0]), int(issueobject[i].raw[u'fields'][u'created'].split('T')[1].split(':')[1])))
ymd_resdate.append(d.datetime(int(issueobject[i].raw[u'fields'][u'resolutiondate'].split('T')[0].split('-')[0]), int(issueobject[i].raw[u'fields'][u'resolutiondate'].split('T')[0].split('-')[1]), int(issueobject[i].raw[u'fields']
[u'resolutiondate'].split('T')[0].split('-')[2]), int(issueobject[i].raw[u'fields'][u'resolutiondate'].split('T')[1].split(':')[0]), int(issueobject[i].raw[u'fields'][u'resolutiondate'].split('T')[1].split(':')[1])))
delta_t.append((ymd_resdate[i] - ymd_create[i]).days)
self.result = np.median(np.array(delta_t))
return self.result
def variancetime(self, issueobject):
for i in range(0, len(issueobject)):
ymd_create.append(d.datetime(int(issueobject[i].raw[u'fields'][u'created'].split('T')[0].split('-')[0]), int(issueobject[i].raw[u'fields'][u'created'].split('T')[0].split('-')[1]), int(issueobject[i].raw[u'fields']
[u'created'].split('T')[0].split('-')[2]), int(issueobject[i].raw[u'fields'][u'created'].split('T')[1].split(':')[0]), int(issueobject[i].raw[u'fields'][u'created'].split('T')[1].split(':')[1])))
ymd_resdate.append(d.datetime(int(issueobject[i].raw[u'fields'][u'resolutiondate'].split('T')[0].split('-')[0]), int(issueobject[i].raw[u'fields'][u'resolutiondate'].split('T')[0].split('-')[1]), int(issueobject[i].raw[u'fields']
[u'resolutiondate'].split('T')[0].split('-')[2]), int(issueobject[i].raw[u'fields'][u'resolutiondate'].split('T')[1].split(':')[0]), int(issueobject[i].raw[u'fields'][u'resolutiondate'].split('T')[1].split(':')[1])))
delta_t.append((ymd_resdate[i] - ymd_create[i]).days)
self.result = np.var(np.array(delta_t))
return self.result

Categories

Resources