How to compare a google datastore datetime to python datetime? - python

I am trying to write a function in python that deletes entries in my datastore that are more than five minutes old. I'm making a kitten picture database for a class, so my code looks something like this:
class KittenImg(db.Model):
"""Models a Gallery entry with kitten_name, image, and date."""
kitten_name = db.StringProperty(multiline=True)
image = db.BlobProperty()
date = db.DateTimeProperty(auto_now_add=True)
A user uploads a KittenImg and it loads into the datastore and returns just fine, but I don't think I understand really what format a kitten.date value would return and how I can compare it to datetime.now() using Python. I have tried a few different options in the python datetime module documentation, but I just really don't think I have a good enough understanding of what I'm getting when I call datetime.now() and when I ask for a kitten.date.
I feel like after looking at the documentation for about three hours, I still have no idea how to even begin getting the solution.
I've been trying things like:
now = datetime.now()
then = kitten.date
tdelta = now - then
And:
now = total_seconds(datetime.now())
then = total_seconds(kitten.date)
tdelta = now - then
But in each case, it gives me an unauthorized operator for the - sign.
It seems like datetime.timedelta() should have something to do with it, but I have absolutely no idea how to use that function even after staring at it for hours.
Can someone please help me either:
1. Understand what's going on with the datetime module better or
2. Give me another way to approach my problem?
Thanks

Sorry, I answered my own question. I must have been doing something different last night, but I got it to work tonight. This is what I did:
for kitten in kittens:
then = kitten.date
now = datetime.datetime.now()
tdelta = now - then
if tdelta.total_seconds() > 300:
kitten.delete()
Should probably have put a static of FIVE_MIN instead of using the magic number 300, so forgive me for that, but it worked.

Related

Search weather.gov API with Python and return data that corrolates to my search criteria

I've been trying to learn Python over the weekend by doing a project and I got stuck. I am doing an API call to https://api.weather.gov/gridpoints/LOT/74,75/forecast . This is a 7 or 10 day forecast. What I am trying to accomplish is passing a data parameter as a string and returning the 'shortForecast' for that date. I have been able to use parsing to find what I'm looking for but I can't seem to find something that will let me search and just return what I need. It also doesn't help that the dates on the API have a time appended to it, so I would have to search for only the first ten digits (2022-08-21). I'm not sure if that matters or not. I've looked into manipulating data dictionaries but all my queries failed.
local_weather_api = requests.get('https://api.weather.gov/gridpoints/LOT/74,75/forecast')
local_weather_data = local_weather_api.text
parse_json = json.loads(local_weather_data)
#current weather
#weatherWanted = parse_json['properties']['periods'][0]['detailedForecast']
#shortForecast
currentShortForecast = parse_json['properties']['periods'][0]['shortForecast']
currentShortForecast1 = parse_json['properties']['periods'][1]['shortForecast']
currentShortForecast2 = parse_json['properties']['periods'][3]['shortForecast']
currentShortForecast3 = parse_json['properties']['periods'][5]['shortForecast']
currentShortForecast4 = parse_json['properties']['periods'][7]['shortForecast']
currentShortForecast5 = parse_json['properties']['periods'][9]['shortForecast']
Any help or a point in the right direction would be appreciated. Thanks

How do I display data from mongodb to a flask template using flask_pymongo?

Sorry if this question is a bit vague. I would like to display data from mongodb to a flask template, but I'm having troubles. This is what I have at this moment, but as you can see, it doesn't work. (I tried to be creative)
#app.route('/find')
def find():
collection = db.lists.find()
names = []
for data in collection:
names.append(data['name'])
return render_template("find.html", title="Find - Website", name=names)
I know that there has to be a better way to do it, and I would really appreciate it if somebody could show me. Thanks!!
Not fully sure what is the end goal. However this is something I have used in couple of my projects before.If you want to show a table output with columns you can maybe leverage pandas and the pandas.to_html function. Something like below - I havent tested the syntax though - please do check from your end
`df = pd.DataFrame.from_dict(json_normalize(db.lists.find))
return render_template("find.html", title="Find - Website", tables = [df.to_html(classes='dfstyle',header='true')]`
you might have to import packages like jsonify from flask , pandas and pandas.io.json.json_normalize from python

Convert Instagram response device time stamp to readable date time

I'm using Instagram-API-python to create an application. I'm getting a JSON response with below value.
'device_timestamp': 607873890651
I tried to convert this value to readable using python.
import time
readable = time.ctime(607873890651)
print(readable)
It gives following result and seems it is not correct.
Sun Oct 3 16:00:51 21232
I'm not much familiar with the Instagram-API-python. Please someone can help me to solve this problem.
The data is very likely to be incorrect.
Timestamp is a very standard way to store a date-time. Counting the seconds that passed since January 1st, 1970, also known as the UNIX Epoch.
I looked for "Instagram 'device_timestamp'" on Google and all the user-provided values made sense, but yours doesn't.
This is probably an error from the database, it happens.
Use the mentioned ctime conversion, but take the 'taken_at' field if available.
Don't use device_timestamp but use taken_at field. Then taken_at need multiply to 1000.
In Java it looks like this
Date data = new Date(taken_at * 1000);

Python and module - date

If I don't have access to the Python time module, how would I determine the number of days that have passed since I was born? That is, within the code, how many days old I am?
The code I am trying to understand better is this:
import time
start = raw_input(“Enter the time stamp in seconds: “)
start = float(start)
end = time.time()
elapsed = end - start
st_elapsed = time.gmtime(elapsed)
print "\n"
hours_mins_secs = time.strftime("%H:%M:%S", st_elapsed)
print "Elapsed time in HH:MM:SS ->", hours_mins_secs, "\n"
Now, I looked to the site https://docs.python.org/2/library/time.html
but I didn't find the alternative related to time, without using module time.
My goal is understand better this code.
This sounds like a homework question. You should give us what you've done so far and we will help you. SO users are not your personal coders.
(No criticism intended)

Python Storm ORM, how to work with time field types

According to this table https://storm.canonical.com/Manual#Table_of_properties_vs._python_vs._database_types, working with MySQL Time fields, you have to use python's time type.
And how would I do that?
Let's say I want to save 9:30, or anything in the database...
import time
storm_object = StormObject()
storm_object.time = time.time() #this raises TypeError: Expected time, found 11... (some number)
storm_object.time = time.strptime('9:30') #this raises TypeError: Expected time, found time.struct_time...
Help?
Guess I was using the wrong module... Not very straight forward behind python newbie's eyes:
import date
storm_object = StormObject()
storm_object.time = datetime.time(9, 30)
store.add(storm_object)

Categories