Jira python calculate time - python

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

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

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?

rSimple python schedule two timed events

I am having trouble with the following scenario using python schedule module. Essentially I want to run a login event at time A, and then run the action at time B.
The code does not run as the intended behaviour describes and this is where I need help.
import sched
import datetime
today = datetime.datetime.today()
log = today.replace(hour=11, minute=59, second = 0)
action= today.replace(hour=12, minute=0, second = 0)
scheduler = sched.scheduler(datetime.datetime.today(), time.sleep)
def login_event(name):
print 'EVENT:', datetime.datetime.today(), name
def action_event(name):
print 'EVENT:' datetime.datetime.today(),name
print 'START:', time.time()
scheduler.enter(log, login_event, ('Login'))
scheduler.enter(action, login_event, ('Action'))
scheduler.run()
EDIT I have altered the code to the following but it still doesn't seem right in terms of how best to implement this behaviour.
import sched
import datetime
from datetime import timedelta
import datetime
import time
today = datetime.datetime.today()
log = datetime.datetime.now() + timedelta(minutes=1)# today.replace(hour=12, minute=46, second = 0)
action= log + timedelta(minutes=2)
scheduler = sched.scheduler(time.time, time.sleep)
print datetime.datetime.now
def login_event(name):
print 'Login:', datetime.datetime.now(), name
def action_event(name):
print 'Action:', datetime.datetime.now(), name
print 'Start:', datetime.datetime.now()
scheduler.enter(1, 1, login_event, ('first',))
scheduler.enter(60, 1, action_event, ('second',))
scheduler.run()
The following code hasn't been tested but should be work.
I've put your original code into comment so you can see where you got wrong.
You will probably need to refer the doc: https://docs.python.org/2/library/sched.html
import sched, time
import datetime
today = datetime.datetime.today()
log = today.replace(hour=11, minute=59, second = 0)
action= today.replace(hour=12, minute=0, second = 0)
#scheduler = sched.scheduler(datetime.datetime.today(), time.sleep)
#The first argument of sched.scheduler should be a function that return a number.
scheduler = sched.scheduler(time.time, time.sleep)
def login_event(name):
print 'EVENT:', datetime.datetime.today(), name
def action_event(name):
print 'EVENT:', datetime.datetime.today(),name
print 'START:', time.time()
scheduler.enter is used for relative delay. The correct function to use is scheduler.enterabs
You will need a function to convert datetime to POSIX timestamp.
This can be tricky in python 2.x due to timezone issue.
Refer to this question: Convert datetime to Unix timestamp and convert it back in python
Also, the function takes 4 arguments.
#scheduler.enter(log, login_event, ('Login'))
#scheduler.enter(action, login_event, ('Action'))
scheduler.enterabs(timestamp(log), 0, login_event, ('Login'))
scheduler.enterabs(timestamp(action), 0, action_event, ('Action'))
scheduler.run()
https://github.com/dbader/schedule
By following the pattern linked above I was able to create the desired behaviour using a slightly different schedule module
import schedule
import time
def job():
print("I'm working on job one...")
def job2():
print("I'm working on job two..")
schedule.every().day.at("10:30").do(job)
schedule.every().day.at("10:35").do(job2)
while True:
schedule.run_pending()
time.sleep(1)

parse dates with icalendar and compare to python datetime

I have an .ics file from which I would like to extract all of the events that occur on today's day. I think I'm having trouble converting the icalendar DTSTART and DTEND to python datetimes. I've tried to follow the documentation at icalendar.readthedocs.org. The list I'm getting is empty, which should not be the case.
This is my code:
import urllib2
import json
from datetime import datetime
from icalendar import Calendar, Event, vDatetime
def getTodayEvents(icsFile):
cal = Calendar.from_ical(icsFile)
today = datetime.now().date()
entries = []
for event in cal.walk('VEVENT'):
dtstart = event['DTSTART']
dtend = event['DTEND']
start = vDatetime.from_ical(dtstart) //Trouble here?
end = vDatetime.from_ical(dtend)
if start <= today <= end:
entry = {'summary' : event['SUMMARY'] }
entries.append(entry)
output = json.dumps(entries)
return output //This list is empty
And this is what the and ics entry looks like:
BEGIN:VEVENT
SUMMARY:Jonny Smith
DTSTART;VALUE=DATE:20140731
DTEND;VALUE=DATE:20150802
UID: 12345
CLASS:PUBLIC
PRIORITY:5
DTSTAMP:20141006T160145Z
TRANSP:OPAQUE
STATUS:CONFIRMED
SEQUENCE:0
LOCATION:Mansfield\, GA
X-MICROSOFT-CDO-APPT-SEQUENCE:0
X-MICROSOFT-CDO-BUSYSTATUS:FREE
X-MICROSOFT-CDO-INTENDEDSTATUS:BUSY
X-MICROSOFT-CDO-ALLDAYEVENT:TRUE
X-MICROSOFT-CDO-IMPORTANCE:1
X-MICROSOFT-CDO-INSTTYPE:0
X-MICROSOFT-DISALLOW-COUNTER:FALSE
END:VEVENT
DTSTART, DTEND properties have .dt attribute:
#!/usr/bin/env python
import json
from datetime import date
import icalendar # $ pip install icalendar
today = date.today()
calendar = icalendar.Calendar.from_ical(ics_file)
entries = [dict(summary=event['SUMMARY'])
for event in calendar.walk('VEVENT')
if event['DTSTART'].dt <= today <= event['DTEND'].dt]
print(json.dumps(entries, indent=2, sort_keys=True))
Output
[
{
"summary": "Jonny Smith"
}
]
The event object has a method .decoded(), which gives you either a datetime.date object (as in your case, the .ics only has a date) or a datetime.datetime object. For the datetime.datetime object, you additionally need to convert the correct timezone.
In order to make a unified comparison, I convert everything to a string and then compare the string. This ended up, that I wrote an isEventToday method:
from datetime import datetime, timezone, timedelta
def isEventToday(event):
if event.get('dtstart') == None:
dtstart = ""
else:
temp = event.decoded('dtstart')
if isinstance(temp, datetime):
dtstart = temp.astimezone().strftime("%Y-%m-%d")
else:
dtstart = temp.strftime("%Y-%m-%d")
if event.get('dtend') == None:
dtend = ""
else:
temp = event.decoded('dtend')
if isinstance(temp, datetime):
dtend = temp.astimezone().strftime("%Y-%m-%d")
else:
# dtend for day events is the day AFTER the event, so we
# need to substract one!
dtend = (temp - timedelta(days=1)).strftime("%Y-%m-%d")
today = datetime.today().date().strftime("%Y-%m-%d")
if dtstart != "" and dtstart == today:
return True
if dtend != "" and dtend == today:
return True
if dtstart != "" and dtend != "" and dtstart <= today and today <= dtend:
return True
return False
The code does not look nice to me, but it is working.
Check to see if you've got a discrepancy between data types or content in your if start <= today <= end: comparison. Take a look (in debugger or so) at what are the types and content of those three variables. I think you'll find that the comparison is comparing things that are legal to compare, but not compatible enough to give you the answer you expect (i.e., do the start and end times of this event overlap todays date?)
Your today is a datetime structure, which can be compared to other datetimes as you intend. Perhaps your vDatetime.from_ical(dtstart) is returning something other than a datetime. A quick glance at the source looks like it should be returning a datetime though. Maybe you've got a time zone issue? Look at the content of all three and check which is < or == or > others.
If that's the case, add a time zone to your calls to vDatetime.from_ical() calls;
start = vDatetime.from_ical(dtstart,'Europe/Amsterdam') #or wherever you are
Your time in the .ics indicates Z -- i.e., GMT.
If you need to do more with dates, see working with time.

Categories

Resources