Looking for dates within JSON data using Python

Seeking advice on efficiently searching through JSON data to find today's date/time and retrieve the corresponding value.

Here is a snippet of the JSON data structure:

[
    {
        "startDateTime": "2018-04-11T14:17:00-05:00",
        "endDateTime": "2018-04-11T14:18:00-05:00",
        "oncallMember": [
            "username1"
        ],
        "shiftType": "historical"
    },
    {
        "startDateTime": "2018-04-11T14:18:00-05:00",
        "endDateTime": "2018-04-16T08:00:00-05:00",
        "oncallMember": [
            "username2"
        ],
        "shiftType": null
    },
{
        "startDateTime": "2018-04-16T08:00:00-05:00",
        "endDateTime": "2018-04-23T08:00:00-05:00",
        "oncallMember": [
            "username1"
        ],
        "shiftType": null
    },
    {
        "startDateTime": "2018-04-23T08:00:00-05:00",
        "endDateTime": "2018-04-30T08:00:00-05:00",
        "oncallMember": [
            "username2"
        ],
        "shiftType": null
    },
......continues on for the year

The start/end dates are designed for weekly rotations among members, but exceptions may alter the schedule to daily or otherwise. The goal is to identify today's date and locate the current "oncallMember". Unsure how to navigate between the start and end times for this purpose.

Any assistance would be welcome.

Answer №1

If you want to work with timestamps in Python, the arrow module could be beneficial for you. First, start by obtaining today's timestamp range:

import arrow
today = arrow.now()
(day_start, day_end) = today.span('day')
day_start_timestamp = day_start.timestamp
day_end_timestamp = day_end.timestamp

Next, if your raw data appears as a time duration like "2018-04-16T08:00:00-05:00", consider extracting only the necessary part such as "2018-04-16T08:00:00", and then utilize arrow to convert it into a timestamp:

raw = "2018-04-16T08:00:00"
FORMAT = "YYYY-MM-DDTHH:mm:SS"
obj = arrow.get(raw, FORMAT)
obj_ts = obj.timestamp

Lastly, ensure that the obj_ts falls within the range defined by day_start_timestamp and day_end_timestamp.

If your code needs to run across multiple days, remember to adjust the timestamp range accordingly each day.

Answer №2

Working with JSON and Datetime in Python

Utilize the json library to parse JSON data using json.loads method, converting it into a dictionary.


For converting strings to datetime objects, leverage both the datetime library and the dateutil.parser.parse function.


import json
from dateutil.parser import parse
from datetime import datetime

data = json.loads(json_string)
# where 'json_string' is your actual json data
start_date = data[0]['startDateTime']
parsed_date = parse(start_date)
# this will return the converted datetime object 

After retrieving the date-time information, proceed with additional coding for comparing start and end dates of today, and eventually returning the appropriate oncallMember.

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

Transforming a string list into a list of numeric values

I am dealing with a list that has the following structure: mylist = ['1,2,3'] As it stands, this is a list containing one string. My goal is to transform it into a list of integers like so: mylist = [1,2,3] My attempt using [int(x) for x in m ...

What is the process for generating a new array of objects by leveraging the contents of two given arrays?

In my data collection, I have multiple objects stored in arrays like so: tableCols = [ { "id": 50883, "header": "ABC", "operator": "Sum", "order": 2 }, ...

Exploring the World of GUIs with Python's Tk

I am in search of a helpful resource to guide me on how to connect TKinter with JSON. I would like to input a word, search for that word in the JSON file, and then display the result of the search. Currently, I have my python application running smoothly ...

Guide to incorporating a vector 2 while serializing with JSONcpp

I am trying to convert a vector of Books into json format using jsoncpp. Despite following the model provided in this tutorial on Stack Overflow which uses a map, I am having trouble getting my data in the desired json format. struct Book { std::string bo ...

matching parentheses in python with stack algorithm

I'm working on implementing a stack to validate parenthesis, but I'm having trouble getting the correct output with the code below. Despite reviewing it multiple times, I can't seem to identify the mistakes. Any suggestions or assistance wou ...

Manipulate Json in jq with Shell Script

I am currently working on a shell script that updates specific values within a JSON array, which is stored in a separate file. The basic logic behind this script involves setting an environment variable called URL, pinging that URL, and then modifying the ...

Avoid Sitecore Page Editor Errors by Saving Returns

I encountered an error when trying to save a page in the page editor. Interestingly, when I edit the page from presentation > detail and then display it in the page editor, everything works fine. Below are the details of the error logs: ERROR After parsin ...

Python text parallel word finding has a scaling issue

In my current Python project, I am facing a task that involves processing sets of names within a corpus of sentences. The goal is to generate a dictionary mapping each name from the set to its occurrences in the corpus, identified by sentence and word indi ...

Are you getting an empty set with your Selenium XPATH query?

I recently checked out this website: After waiting for the page to load, I wrote the following python code: try: tmp = driver.find_elements(By.XPATH, '//*[text()="Login"]') print(tmp) except Exception as e: print('NONE ...

Scraping the web: Encountering the ' ' tag when extracting data using Beautiful Soup

I'm attempting to extract data from the table on a Wikipedia page Link. When trying to separate each column by ',' to save it in a CSV file, I encounter an error due to the presence of '/n' tags. For example, the output for row 1 ...

Is there a way to simulate pressing shift + enter key with Python using Selenium Chrome WebDriver?

I recently developed a bulk WhatsApp message sender application that allows for sending multi-line text messages. However, I encountered an issue on WhatsApp web where pressing enter sends the message right away. My goal is to have it press shift + enter ...

How can we transform the input for the prediction function into categorical data to make it more user-friendly?

To verify my code, I can use the following line: print(regressor.predict([[1, 0, 0, 90, 100]])) This will generate an output. The first 3 elements in the array correspond to morning, afternoon, and evening. For example: 1, 0, 0 is considered as morning 0 ...

Parsing a multidimensional array using JSON arrays

My current challenge involves working with an array called jArray, which is structured as follows: {"users":[ { "user_id":6, "user_name":"Ted Vanderploeg", "email":"<a href="/cdn-cgi/l/email ...

Issues with Python class constructor inheritance: Seeking guidance on correct implementation

I encountered an issue with my Python OOP program that involves two classes, Flan and Outil, inheriting from a superclass called Part. When I call Flan, everything functions perfectly, but when I call Outil, the program fails without any error messages. ...

Combining lists of key-value pairs

How can I combine two arrays of dictionaries to create a new array that only includes the dictionaries with the highest version value? data1 = [{'id': 1, 'name': 'Oneeee', 'version': 2}, {'id': 2, ...

Is there a way to eliminate empty arrays from my data?

I'm dealing with this PHP code snippet. public function display_children($parent,$level){ try { $cmd = $this->connection->prepare('SELECT mem,pid from mytree where pid = ?'); $cmd->execute(array($parent)); ...

Distributing data from a JSON object into various classes

I am currently exploring a method to allocate certain properties of the "participants" objects into specific classes: This is the data format I am working with "participants": [ { "person_id": "18044029", "role_id": "35351535", ...

Reduce JSON for efficient deserialization and persistence of intricate POJOs using JPA/Hibernate

Dealing with deserialization of a complex POJO from a JSON string and persisting it in a MySQL database can be quite challenging. Below is a simplified example class: @Entity @Table(name="a") public class A{ private Long id; private B b; priva ...

Ways to categorize JSON information

Is it possible to group JSON data by group_name? JSON : [ {"fullname":"fffffffff","email":"sss@gg","mobile":"3333333333","designation":"ggg","group_name":"engineers"}, {"fullname":"ddddddddddd","email":"sssg@gg","mobile":"3333333333","designation":"ffff ...

Issue encountered when attempting to retrieve JSON data from a table containing multiple rows

Setting: My current setup involves using Oracle 19c database with PLSQL JSON functions like JSON_TABLE. The Task at Hand: My goal is to extract JSON data from a CLOB column within a table that contains multiple rows. Dilemma: I have encountered an issue ...