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))
Related
I've been working on some code to track stocks and have been using the datetime function to get x number or days ago, decided by user input. However, I have been getting the error
line 12, in
amount_Of_Days_Ago = today - datetime.datetime.timedelta(days=amount_Of_Days_Ago)
AttributeError: type object 'datetime.datetime' has no attribute 'timedelta'
Here's my code
import datetime
print('How many days ago should the smaller period of time be?')
amount_Of_Days_Ago = input()
amount_Of_Days_Ago = int(amount_Of_Days_Ago)
today = datetime.datetime.now()
amount_Of_Days_Ago = today - datetime.datetime.timedelta(days=amount_Of_Days_Ago)
amount_Of_Days_Ago = amount_Of_Days_Ago.strftime('%Y-%m-%d')
today = today.strftime('%Y-%m-%d')
amount_Of_Days_Ago = str(amount_Of_Days_Ago)
today = str(today)
response = requests.get("http://api.marketstack.com/v1/eod?access_key=###########&symbols=AAPL&date_from=" + amount_Of_Days_Ago + "&date_to=" + today)
print(response)
Indeed, there is only the need to call datetime once after importing it.
Have a look at the docs here. Consider using:
amount_Of_Days_Ago = today - datetime.timedelta(days=amount_Of_Days_Ago)
Or:
from datetime import timedelta
amount_Of_Days_Ago = today - timedelta(days=amount_Of_Days_Ago)
You have to import the timedelta function from the datetime library. As in:
import datetime
from datetime import timedelta
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")
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
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?
I am looking for a comparison of two times in Python. One time is the real time from computer and the other time is stored in a string formatted like "01:23:00".
import time
ctime = time.strptime("%H:%M:%S") # this always takes system time
time2 = "08:00:00"
if (ctime > time2):
print("foo")
import datetime
now = datetime.datetime.now()
my_time_string = "01:20:33"
my_datetime = datetime.datetime.strptime(my_time_string, "%H:%M:%S")
# I am supposing that the date must be the same as now
my_datetime = now.replace(hour=my_datetime.time().hour, minute=my_datetime.time().minute, second=my_datetime.time().second, microsecond=0)
if (now > my_datetime):
print("Hello")
EDIT:
The above solution was not taking into account leap second days (23:59:60). Below is an updated version that deals with such cases:
import datetime
import calendar
import time
now = datetime.datetime.now()
my_time_string = "23:59:60" # leap second
my_time_string = now.strftime("%Y-%m-%d") + " " + my_time_string # I am supposing the date must be the same as now
my_time = time.strptime(my_time_string, "%Y-%m-%d %H:%M:%S")
my_datetime = datetime.datetime(1970, 1, 1) + datetime.timedelta(seconds=calendar.timegm(my_time))
if (now > my_datetime):
print("Foo")
https://docs.python.org/2/library/datetime.html
The datetime module will parse dates, times, or combined date-time values into objects that can be compared.
from datetime import datetime
current_time = datetime.strftime(datetime.utcnow(),"%H:%M:%S") #output: 11:12:12
mytime = "10:12:34"
if current_time > mytime:
print "Time has passed."