Comparing datetime to a time range - python

I have a datetime object representing when a user logged, from this object I want to check whether the datetime object expresses a date in the range today -7, so if today is 2018-06-21 I would like to return ever date between today and 2018-06-14. I attach an example of my code (terribly wrong).
def joined_today(self, query):
filtered = []
today = datetime.today().date()
for x in query:
if x[1].date() = today -7:
filtered.append(x)
return filtered

A couple of things here. Firstly, you can do date calculations using datetime.timedelta. And secondly, you don't want to check that the date is equal to "today - 7", you want to check it is greater than that and less than or equal to today. So:
seven_days_ago = today - timedelta(days=7)
for x in query:
if seven_days_ago < x[1].date() <= today:
...

Related

Printing working dates between two dates but excluding every weekends

I am trying to print the working days between two dates, but excluding the latter one and the weekends, holding in there. I've tried the following code:
from datetime import timedelta, date, datetime
def print_working_dates(date1, date2):
excluded = (6,7)
for n in range(int((date2 - date1).days)+1):
if date1.isoweekday == excluded:
continue
else:
yield date1 + timedelta(n)
start_dt = datetime.now()
end_dt = datetime(2022, 4, 28)
for dt in print_working_dates(start_dt, end_dt):
print(dt.strftime("%Y-%m-%d"))
which prints every day before the last one, but it holds all weekends. Could anyone please anyone could give a piece of advice to define better this function? To my mind, the excluded object should be better detailed, but I cannot know how.
Firstly, you can check if a value is in an iterable (such as a tuple or list) using the in keyword. isoweekday is a function, so you need to call it with isoweekday(). Finally, you need to work out the new date, then check it's weekday, otherwise it just checks if the start date is a weekend for every date.
def print_working_dates(date1, date2):
excluded = (6,7)
for n in range(int((date2 - date1).days)+1):
new = date1 + timedelta(n)
if new.isoweekday() not in excluded:
yield new
I've negated the if statement with not to make it a bit more compact.
First off, you are not checking the correct time to be a weekday or not you have to check if (date1 + timedelta(n)) is a weekday, not date1
And secondly you have to you have to check if isoweekday's return value is in the excluded
Here's my solution to your code:
from datetime import timedelta, datetime
def print_working_dates(date1, date2):
excluded = (6,7)
for n in range(int((date2 - date1).days)+1):
if (date1 + timedelta(n)).isoweekday() in excluded:
continue
else:
yield date1 + timedelta(n)
start_dt = datetime.now()
end_dt = datetime(2022, 4, 28)
for dt in print_working_dates(start_dt, end_dt):
print(dt.strftime("%Y-%m-%d"))

How to write a python function that returns the number of days between two dates

I am new to functions and I am trying to write a function that returns the number of days between two dates:
My attempt:
import datetime
from dateutil.parser import parse
def get_x_days_ago (date_from, current_date = None):
td = current_date - parse(date_from)
if current_date is None:
current_date = datetime.datetime.today()
else:
current_date = datetime.datetime.strptime(date_from, "%Y-%m-%d")
return td.days
print(get_x_days_ago(date_from="2021-04-10", current_date="2021-04-11"))
Expected outcome in days:
1
So there seem to be multiple issues, and as I said in the comments, a good idea would be to separate the parsing and the logic.
def get_x_days_ago(date_from, current_date = None):
if current_date is None:
current_date = datetime.datetime.today()
return (current_date - date_from).days
# Some other code, depending on where you are getting the dates from.
# Using the correct data types as the input to the get_x_days_ago (datetime.date in this case) will avoid
# polluting the actual logic with the parsing/formatting.
# If it's a web framework, convert to dates in the View, if it's CLI, convert in the CLI handling code
date_from = parse('April 11th 2020')
date_to = None # or parse('April 10th 2020')
days = get_x_days_ago(date_from, date_to)
print(days)
The error you get is from this line (as you should see in the traceback)
td = current_date - parse(date_from)
Since current_date="2021-04-11" (string), but date_from is parsed parse(date_from), you are trying to subtract date from the str.
P.S. If you have neither web nor cli, you can put this parsing code into def main, or any other point in code where you first get the initial strings representing the dates.
It looks like you're already aware that you can subtract a datetime from a datetime. I think, perhaps, you're really looking for this:
https://stackoverflow.com/a/23581184/2649560

create a list of dates with a while loop python

I want tot create a list of dates starting from 10/09/2020 with increments of 182 days until reaching 05/03/2020.
my code is this :
start_date="10/09/2020"
last_date="05/03/2020"
start_date=datetimedatetime.strptime(date,"%d/%m/%Y").date()
last_date=datetimedatetime.strptime(date,"%d/%m/%Y").date()
dates=[]
while dates[-1] != last_date:
i=star_date+timedelta(days=182)
dates.append(i)
dates[i]=i+timedelta(days=pago_cupon)
I don't know what's your problem.
You can try this code
from datetime import date, timedelta
start_day = date(year=2020, month=9, day=10)
end_day = date(year=2021, month=3, day=5)
one_data_delta = timedelta(days=1)
res = []
while end_day != start_day:
start_day += one_data_delta
res.append(start_day)
print(res)
A few problems:
You had a spelling mistake in your for loop star_date instead of start_date.
Also, you may want to change the comparison from != to less than equals or more than equals.
I am checking against (last_date - timedelta(days=182)) so that we won't exceed the last_date.
Your original start date is after your original end date.
As an example, I have adjusted the end day to be a couple years in the future.
I'm appending the dates as text.
from datetime import datetime, timedelta
start="10/09/2020"
last="05/03/2022"
start_date=datetime.strptime(start,"%d/%m/%Y")
last_date=datetime.strptime(last,"%d/%m/%Y")
dates=[]
while start_date <= (last_date - timedelta(days=182)):
start_date += timedelta(days=182)
dates.append(start_date.strftime("%d/%m/%Y"))
# not quite sure what you are trying to do here:
#dates[i]=i+timedelta(days=pago_cupon)
print(dates)
Output:
['11/03/2021', '09/09/2021']

How to check if a certain date is present in a dictionary and if not, return the closest date available?

I have a dictionary with many sorted dates. How could I write a loop in Python that checks if a certain date is in the dictionary and if not, it returns the closest date available? I want it to work that if after subtracting one day to the date, it checks again if now it exists in the dictionary and if not, it subtracts again until it finds a existing date.
Thanks in advance
from datetime import timedelta
def function(date):
if date not in dictio:
date -= timedelta(days=1)
return date
I've made a recursive function to solve your problem:
import datetime
def find_date(date, date_dict):
if date not in date_dict.keys():
return find_date(date-datetime.timedelta(days=1), date_dict)
else:
return date
I don't know what is the content of your dictionary but the following example should show you how this works:
import numpy as np
# creates a casual dates dictionary
months = np.random.randint(3,5,20)
days = np.random.randint(1,30,20)
dates = {
datetime.date(2019,m,d): '{}_{:02}_{:02}'.format(2019,m,d)
for m,d in zip(months,days)}
# select the date to find
target_date = datetime.date(2019, np.random.randint(3,5), np.random.randint(1,30))
# print the result
print("The date I wanted: {}".format(target_date))
print("The date I got: {}".format(find_date(target_date, dates)))
What you are looking for is possibly a while loop, although beware because if it will not find the date it will run to infinite. Perhaps you want to define a limit of attempts until the script should give up?
from datetime import timedelta, date
d1 = {
date(2019, 4, 1): None
}
def function(date, dictio):
while date not in dictio:
date -= timedelta(days=1)
return date
res_date = function(date.today(), d1)
print(res_date)

How to compare dates in sqlalchemy?

I have the following simple setup, where fromDate and toDate are strings on the format "YYYY-MM-DD":
class SomeType(Base):
date = Column(DateTime)
def findAll(fromDate, toDate):
return session.query(SomeType).filter(SomeType.date >= fromDate, SomeType.date <= toDate).all()
The problem is that it doesn't find what I want it to find unless I modify the input dates like this:
def findAll(fromDate, toDate):
fromDate = fromDate + " 00:00"
toDate = toDate + " 24:00"
return session.query(SomeType).filter(SomeType.date >= fromDate, SomeType.date <= toDate).all()
But that doesn't look good. Any ideas on how I can do this the right way?
How about using datetime.datetime objects instead of strings for fromDate, toDate?
from datetime import datetime, timedelta
def findAll(fromDate, toDate):
fromDate = datetime.strptime(fromDate, '%Y-%m-%d')
toDate = datetime.strptime(toDate, '%Y-%m-%d') + timedelta(days=1)
return session.query(SomeType).filter(
SomeType.date >= fromDate,
SomeType.date < toDate).all()
The problem is that your SomeType.date column is not simple date, but is datetime column, so it contains also a time component.
This type mismatch is the cause of your problem. If this is the case then following should work:
session.query(SomeType).filter(func.date(SomeType.date) >= fromDate, func.date(SomeType.date) <= toDate).all()
where we basically cast datetime to date using DATE(...) function of MySql.
However, I would probably also prefer working with date(time) data types instead of strings. You are just lucky that most databases implicitly allow parsing of ISO-compliant string representations of DATEs.
I know this is old, but while trying to find my answer, I found datetime.combine
you can do
select(SomeTable)
.filter( SomeTable.datetime_issued >= datetime.combine(start_date, time.min),
SomeTable.datetime_issued <= datetime.combine(end_date, time.max))
datetime.combine will combine date and time into datetime
https://docs.python.org/3/library/datetime.html#datetime.datetime.combine
When combining, you should use time.min, time.max which will give you min and max time
print(combine(date.today(), time.min), combine(date.today(), time.max))
This will print
2022-10-14 00:00:00, 2022-10-14 23:59:59.999999
https://docs.python.org/3/library/datetime.html#datetime.time.max

Categories

Resources