Using timedelta to filter data when a field may be missing

I'm attempting to develop a function within the PlayerAt table to retrieve records from a PlayerOc table based on a filter that utilizes the timedelta feature. Below is an abbreviated version of the class:

class PlayerAt(Base):

    id_ = sa.Column(sa.Integer, primary_key=True)
    birth_date = sa.Column(sa.Date, index=True)

    def return_player_oc_records(self):
        session = sa.orm.object_session(self)
        qry = session.query(PlayerOc)
        qry = qry.outerjoin(PlayerAt)
        qry = qry.filter(PlayerOc.birth_date >= self.birth_date - dt.timedelta(weeks=4))
        recs = qry.all()
        return recs

However, upon executing the function, I encounter the following error:

TypeError: unsupported operand type(s) for -: 'NoneType' and 'datetime.timedelta'

This arises because certain records in the PlayerAt table lack a birth_date entry.

I've attempted converting the filter to:

qry = qry.filter(PlayerOc.birth_date >= sa.func.IF(self.birth_date != None, self.birth_date - dt.timedelta(weeks=4), None))

Nevertheless, I receive the same error message.

Any suggestions for resolving this issue?

Answer №1

One way to filter results is by using the following code

qry = qry.filter((self.birth_date.isnot(None)) & (PlayerOc.birth_date >=  self.birth_date - dt.timedelta(weeks=4)))

To include no birthday in your filter, you can also use the following code with an or condition

qry = qry.filter((self.birth_date.is_(None)) | (PlayerOc.birth_date >=  self.birth_date - dt.timedelta(weeks=4)))

Answer №2

I discovered a solution using the DATEDIFF function in this manner:

qry = qry.filter(sa.func.datediff(PlayerOc.birth_date, self.birth_date) >= -28)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Encountering a TypeError while attempting to utilize Django and Pandas for displaying data in an HTML format

import pandas as pd from django.shortcuts import render # Define the home view function def home(): # Read data from a CSV file and select only the 'name' column data = pd.read_csv("pandadjangoproject/nmdata.csv", nrows=11) only_city ...

An error of 'Address already being used' encountered while utilizing cookiecutter-flask

My operating system is OS X 10.14.3 and I am attempting to utilize the impressive cookiecutter-flask project. I have diligently followed the instructions provided in the README.rst: cookiecutter https://github.com/sloria/cookiecutter-flask.git # My test p ...

Automate Citrix web tasks using Selenium or similar tools for efficient and streamlined processes

Are there any methods for implementing selenium or a similar tool on Citrix web systems? I have been relying on pyautogui, but it seems to be quite ineffective by itself. Any suggestions on how to enhance pyautogui would be greatly appreciated. ...

Ordering Django objects by their creation date within the last week

models.py class short_url(models.Model): """ This is a short_url class """ blocked = models.BooleanField(default=False) updated_at = models.DateTimeField(auto_now=True) ...

Generating a backup of the database using the web application's graphical user interface

Does anyone know if it's possible to create a database dump or back up data directly from the browser interface? I'm looking for a way to back up my database within my web application. ...

Steps to create every combination of character pairs in a given string

Is there a way to create all possible pair combinations of characters from a given string? # Example: s = "ABCD" # Expected output: ["A", "BCD"] ["B", "ACD"] ["C", "ABD"] ... ["AB", "CD"] ... ["BC", "AD"] ... ["ABC", "D"] ["ABD", "C"] ["ACD", "B"] ["BCD ...

Steps for creating a while loop that continuously inputs prices until the user enters 0:

I am hoping to create a simple Python code that allows users to input prices from a shopping trip, with the loop ending when they input 0. Once the loop stops, I'd like to display the total number of items, average price, and total price using an else ...

The JSON index is beyond the range [0..1)

I have been attempting to retrieve data from a MySql database using Volley in a JSONArray. The PHP script used to fetch rows from the table is shown below: <?php ob_start(); header('Content-Type: application/json'); $con=mysqli_connect("local ...

Adding a basic function within a Django HTML template can enhance the functionality and flexibility

Currently, I have a function named "copyright" in my project that generates a dynamic copyright message. My goal is to incorporate this function into my base Django template as shown below: def copyright(): // code here // more code here print(fi ...

Exploring the power of Django and S3 for seamless direct uploading capabilities

Within my current project, I have successfully implemented and configured S3 storages. However, I am now in the process of setting up direct uploads to S3 using s3 direct. While most of it is functioning properly - allowing users to upload images directly ...

Create parallel edges in networkx

Here is a straightforward example for you to consider: import networkx as nx import matplotlib.pyplot as plt g = nx.DiGraph() g.add_nodes_from([1,2,3]) g.add_edge(1,2, weight=1) g.add_edge(1,3, weight=1) g.add_edge(2,1, weight=2) nx.draw(g, with_labels=T ...

Is it necessary to call file.close() when encountering a FileNotFoundError exception while closing a file?

As I work on a Python project, I encountered a situation where I need to open a file and display a message if the file does not exist. However, I am unsure whether it is necessary to close the file when an exception occurs. try: file = open(s ...

"Encountered a MySQL error while attempting to perform an update

I have a question: Within my database, there are 2 tables: articles: id useid title users id name surname In my view: Author<select name="author" id="author"> <?php foreach ($users as $u): ?> ...

What steps should I take to fix the connection between my Node application and MySQL using the hostname?

*** Changed the username from 'sabcozac@user' to 'sabcozac_user' Encountering a problem with my connection to the hosted MySQL database as the hostname is being added automatically, even though I haven't specified it anywhere in m ...

The webcam stream cannot be accessed: VideoCapture error

I'm currently using Windows10 to write code in Python. I am attempting to capture a live stream from my webcam. webcam = cv2.VideoCapture(0) (rval, im) = webcam.read() Upon checking the value of 'im', it appears to be 'None'. Is ...

Waiting for elements to be loaded in Selenium and Python: A step-by-step guide

Imagine I am choosing with the following selector: //img[@data-blabla] If I want to wait for 10 elements to be loaded, not just one, how should this be altered? My assumption is to use the index [9] WebDriverWait(browser, 5).until(EC.presence_of_element_l ...

Is it possible for me to customize the MySQL query based on the user input using PHP?

I am facing a unique situation where the query depends on user input. When the user enters "toy," the query includes certain conditions, and when they enter "TV," the query changes slightly. This method works fine for a few products, but I have many diff ...

Making changes to a SQLite table by comparing it with another table to find matches

I need to perform an update on a table named stock where the product_id matches the product_id of another table called stock_in_temp, and also ensure that a column named crm_product_id is either null or ''. This task needs to be done using python ...

PyQt5 Code in Eclipse (PyDev) experiencing exception without traceback information retrieved

Although this question may sound familiar, it remains unanswered for over a year. I am sharing more details in hopes of finally getting a resolution. The problem arises when the code enters PyQt5's loops and a crash occurs without displaying the trac ...

Tips for capturing network traffic with Selenium WebDriver and BrowserMob Proxy in Python

For my project, I am working on capturing network traffic using Selenium Webdriver with Python. In order to achieve this, I need to utilize a proxy such as BrowserMobProxy. Everything works smoothly when using webdriver.Chrome: from browsermobproxy impor ...