how to set timezone in local variable using python? - 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")

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

Python 3.8 datetime date comparison not work between "internal generated date" and imported date

I'm trying to compare the actual date with externally generated date, always generated from datetime but in another script and saved in a txt file.
This is the code:
import datetime
datin = datetime.datetime.today()
with open('date.txt', 'r') as mydate:
mdate = mydate.read()
datex = datetime.datetime.strptime(mdate, '%d-%m-%Y')
if datin.date == datex.date:
print('=')
else:
print('!=')
print(datin.strftime('%d-%m-%Y'))
print(datex.strftime('%d-%m-%Y'))
this is the txt file:
03-07-2020
(the same date I'm testing the script)
should return = but return !=
What am I doing wrong?
You have a slight error in that you are accessing the method of the date objects instead of calling the method.
You can find this out by trying to print
datin.date versus datin.date()
Here is the corrected code that runs as expected:
import datetime
datin = datetime.datetime.today()
mdate = '03-07-2020'
datex = datetime.datetime.strptime(mdate,"%d-%m-%Y")
print(datin.date())
print(datex.date())
if datin.date() == datex.date():
print("=")
else:
print("!=")
print (datin.strftime("%d-%m-%Y"))
print(datex.strftime("%d-%m-%Y"))

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

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