Counting day-of-week-hour pairs between two dates

2024/10/3 19:20:43

Consider the following list of day-of-week-hour pairs in 24H format:

{'Mon': [9,23],'Thu': [12, 13, 14],'Tue': [11, 12, 14],'Wed': [11, 12, 13, 14]'Fri': [13],'Sat': [],'Sun': [],
}

and two time points, e.g.:

  • Start:

    datetime.datetime(2015, 7, 22, 17, 58, 54, 746784)
    
  • End:

    datetime.datetime(2015, 8, 30, 10, 22, 36, 363912)
    

Say we need to know how many hours there are between these two datetimes (either rounding up or down) for each of the day-of-week-hour pairs specified above.

How can I approach this problem in Python? I explored timedelta and relativedelta in a general level of detail but I didn't find anything that provides something close to this.

For simplicity, we can assume that everything refers to the same timezone.


Perhaps a simpler problem is to focus on a single day-hour pair, e.g. How many Wednesdays: 14 are there between two arbitrary datetimes?

Answer

Perhaps something like this:

from calendar import day_abbr
from datetime import datetime, timedeltadef solve(start, end, data):days = list(day_abbr)output = dict.fromkeys(days, 0)while start <= end:day = days[start.weekday()]if start.hour in data[day]:output[day] += 1start = start + timedelta(minutes=60)return outputdata = {'Mon': [9, 23],'Thu': [12, 13, 14],'Tue': [11, 12, 14],'Wed': [11, 12, 13, 14],'Fri': [13],'Sat': [],'Sun': [],
}start = datetime(2015, 7, 22, 17, 58, 54, 746784)
end = datetime(2015, 8, 30, 10, 22, 36, 363912)print solve(start, end, data)
# {'Wed': 20, 'Sun': 0, 'Fri': 6, 'Tue': 15, 'Mon': 10, 'Thu': 18, 'Sat': 0} 

Getting count for each day by hour:

from calendar import day_abbr
from collections import defaultdict
from datetime import datetime, timedelta
from pprint import pprintdef solve(start, end, data):days = list(day_abbr)output = defaultdict(lambda: defaultdict(int))while start <= end:day = days[start.weekday()]if start.hour in data[day]:output[day][start.hour] += 1start = start + timedelta(minutes=60)return {k: dict(v) for k, v in output.items()}data = {'Mon': [9, 23],'Thu': [12, 13, 14],'Tue': [11, 12, 14],'Wed': [11, 12, 13, 14],'Fri': [13],'Sat': [],'Sun': [],
}start = datetime(2015, 7, 22, 17, 58, 54, 746784)
end = datetime(2015, 8, 30, 10, 22, 36, 363912)pprint(solve(start, end, data))
# output 
{'Fri': {13: 6},'Mon': {9: 5, 23: 5},'Thu': {12: 6, 13: 6, 14: 6},'Tue': {11: 5, 12: 5, 14: 5},'Wed': {11: 5, 12: 5, 13: 5, 14: 5}}
https://en.xdnf.cn/q/70698.html

Related Q&A

Download A Single File Using Multiple Threads

Im trying to create a Download Manager for Linux that lets me download one single file using multiple threads. This is what Im trying to do : Divide the file to be downloaded into different parts by sp…

Merge string tensors in TensorFlow

I work with a lot of dtype="str" data. Ive been trying to build a simple graph as in https://www.tensorflow.org/versions/master/api_docs/python/train.html#SummaryWriter. For a simple operat…

How to reduce memory usage of threaded python code?

I wrote about 50 classes that I use to connect and work with websites using mechanize and threading. They all work concurrently, but they dont depend on each other. So that means 1 class - 1 website - …

Connection is closed when a SQLAlchemy event triggers a Celery task

When one of my unit tests deletes a SQLAlchemy object, the object triggers an after_delete event which triggers a Celery task to delete a file from the drive.The task is CELERY_ALWAYS_EAGER = True when…

Python escape sequence \N{name} not working as per definition

I am trying to print unicode characters given their name as follows:# -*- coding: utf-8 -*- print "\N{SOLIDUS}" print "\N{BLACK SPADE SUIT}"However the output I get is not very enco…

Binary integer programming with PULP using vector syntax for variables?

New to the python library PULP and Im finding the documentation somewhat unhelpful, as it does not include examples using lists of variables. Ive tried to create an absolutely minimalist example below …

Nonblocking Scrapy pipeline to database

I have a web scraper in Scrapy that gets data items. I want to asynchronously insert them into a database as well. For example, I have a transaction that inserts some items into my db using SQLAlchemy …

python function to return javascript date.getTime()

Im attempting to create a simple python function which will return the same value as javascript new Date().getTime() method. As written here, javascript getTime() method returns number of milliseconds …

Pulling MS access tables and putting them in data frames in python

I have tried many different things to pull the data from Access and put it into a neat data frame. right now my code looks like this.from pandas import DataFrame import numpy as npimport pyodbc from sq…

Infinite loop while adding two integers using bitwise operations?

I am trying to solve a problem, using python code, which requires me to add two integers without the use of + or - operators. I have the following code which works perfectly for two positive numbers: d…