How can I get the amount of days between two dates? - python

I got a python script, which is supposed to fetch data of my mysql table (contains a date) and then it should print out the amount of days between today´s date and the date of my mysql table.
I already tried substracting the two dates, but this wouldn´t work. So I tried substracting today´s date and my birthday, which worked. So I think the problem is the mysql date.
import datetime
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="root",
passwd="",
database='appointments'
)
eventDate = mydb.cursor()
eventDate.execute('SELECT event_date FROM appointdatetitle')
Date = eventDate.fetchall()
tdelta = datetime.timedelta(days=7)
today = datetime.date.today()
eday = Date
till_eday = eday - today
print(till_eday.days)

Date = eventDate.fetchall() fetchall actually fetches a tuple of tuples
e.g.
(('abcd',), ('efgh',))
You would want to get the Date by looping over the list and getting the elements. e.g.
for d in Date:
#This will contain the date you need
print(d[0])
Or you can directly access an element by doing say Date[0][0]
After update from OP, this is what can be done!
OP can use https://dateutil.readthedocs.io/en/stable/index.html to use the
from dateutil.relativedelta import * to increment the month!
import datetime
from dateutil.relativedelta import *
Date = [(datetime.date(2019, 4, 24),)]
#Extract actual datetime object from Date variable
date_obj = Date[0][0]
#Increment month by 1 since January starts from 0
date_obj += relativedelta(months=1)
today = datetime.date.today()
#Using datetime from above
eday = date_obj
till_eday = eday - today
print(till_eday.days)
The output will be 23

Related

How to select dates in SQLite with python

Im trying to query a table, and need to grab all products that have a date = today date.
Below is my code so far
import sqlite3
from datetime import date
date = date.today()
con = sqlite3.connect('test.db')
cur = con.cursor()
date = date.today()
sql_q = f'''SELECT date, name FROM table WHERE date = {date}'''
table = cur.execute(sql_q)
for row in table:
print(row)
i am using an SQlite 3 db and all data has been entered with the following format:
2022-09-20
However this variable type does not seem to work with SQL.
i know the SQL code should look somthing like this
SELECT name FROM test WHERE date = '2022-09-20'
but i'd like the date to be selected automatically from python rather than typing it in manually.
Use the function date() to get the current date:
SELECT name FROM test WHERE date = date()
or CURRENT_DATE:
SELECT name FROM test WHERE date = CURRENT_DATE
I think you need to convert date to string and then pass it in query.
maybe your datatype of column and date.today() is different.
date = date.strftime('%Y-%m-%d')
try using this.

In Python I have embedded SQL code with 2 sets of between dates. How to loop the python code to run multiple sets of between dates

I am new to this so sorry if my question is odd or confusing. In python I have an embedded SQL query that has 2 between dates for data. I have several dates I want to loop this code through each 'between date sets' I have for the entire month. I feel like I am missing a package that would help with this and I have not found a tutorial to follow something like this.
Say for example sake.
List of between dates
2020-02-01 AND 2020-02-05,
2020-02-02 AND 2020-02-06,
2020-02-03 AND 2020-02-07,
... all the way to ...
2020-02-28 AND 2020-03-04
Where I am at so far is this and I can't figure out how to setup an array for this.
import psybopg2
import getpass
import pandas
con = psybopg2.connect(host="blah",database="blah",user=getpass.getpass
cur.execute("""
SELECT
Address
,Create_Data
,Event_Date
FROM
table.a
WHERE
Create_Date between '2020-03-20' AND '2020-03-25' --(want to insert set of dates from the list
AND
Event_Date between '2020-03-20' AND '2020-03-25' --(want to insert the same between date used above
""")
output = cur.fetchall ()
data = pd.DataFrame(output)
cur.close()
con.close()`
Use datetime and timedelta:
from datetime import datetime
start_date = "2020-02-01"
stop_date = "2020-02-28"
start = datetime.strptime(start_date, "%Y-%m-%d")
stop = datetime.strptime(stop_date, "%Y-%m-%d")
from datetime import timedelta
while start < stop:
first_date = start #first date for between
second_date = start + timedelta(days=4) #second date for between
#Use the above in sql query
start = start + timedelta(days=1) # increase day one by one

How to get a specific date from the previous month given the current date in python?

I want to get the 20th of previous month, given the current_date()
I am trying to use time.strftime but not able to subtract the value from it.
timestr = time.strftime("%Y-(%m-1)%d")
This is giving me error. The expected output is 2019-03-20 if my current_date is in April. Not sure how to go about it.
I read the posts from SO and most of them address getting the first day / last day of the month. Any help would be appreciated.
from datetime import date, timedelta
today = date.today()
last_day_prev_month = today - timedelta(days=today.day)
twenty_prev_month = last_day_prev_month.replace(day=20)
print(twenty_prev_month) # 2019-03-20
Use datetime.replace
import datetime
current_date = datetime.date.today()
new_date = current_date.replace(
month = current_date.month - 1,
day = 20
)
print(new_date)
#2019-03-20
Edit
That won't work for Jan so this is a workaround:
import datetime
current_date = datetime.date(2019, 2, 17)
month = current_date.month - 1
year = current_date.year
if not month:
month, year = 12, year - 1
new_date = datetime.date(year=year, month=month, day=20)
I imagine it is the way dates are parsed. It is my understanding that with your code it is looking for
2019-(03-1)20 or 2019-(12-1)15, etc..
Because the %y is not a variable, but a message about how the date is to be expected within a string of text, and other characters are what should be expected, but not processed (like "-")
This seems entirely not what you are going for. I would just parse the date like normal and then reformat it to be a month earlier:
import datetime
time = datetime.datetime.today()
print(time)
timestr = time.strftime("%Y-%m-%d")
year, month, day = timestr.split("-")
print("{}-{}-{}".format(year, int(month)-1, day))
This would be easier with timedelta objects, but sadly there isn't one for months, because they are of various lengths.
To be more robust if a new year is involved:
import datetime
time = datetime.datetime.today()
print(time)
timestr = time.strftime("%Y-%m-%d")
year, month, day = timestr.split("-")
if month in [1, "01", "1"]: # I don't remember how January is represented
print("{}-{}-{}".format(int(year) - 1, 12, day)) # use December of last year
else:
print("{}-{}-{}".format(year, int(month)-1, day))
This will help:
from datetime import date, timedelta
dt = date.today() - timedelta(30)// timedelta(days No.)
print('Current Date :',date.today())
print(dt)
It is not possible to do math inside a string passed to time.strftime, but you can do something similar to what you're asking very easily using the time module
in Python 3
# Last month
t = time.gmtime()
print(f"{t.tm_year}-{t.tm_mon-1}-20")
or in Python 2
print("{0}-{1}-{2}".format(t.tm_year, t.tm_mon -1, 20))
If you have fewer constraints, you can just use the datetime module instead.
You could use datetime, dateutil or arrow to find the 20th day of the previous month. See examples below.
Using datetime:
from datetime import date
d = date.today()
month, year = (d.month-1, d.year) if d.month != 1 else (12, d.year-1)
last_month = d.replace(day=20, month=month, year=year)
print(last_month)
Using datetime and timedelta:
from datetime import date
from datetime import timedelta
d = date.today()
last_month = (d - timedelta(days=d.day)).replace(day=20)
print(last_month)
Using datetime and dateutil:
from datetime import date
from dateutil.relativedelta import relativedelta # pip install python-dateutil
d = date.today()
last_month = d.replace(day=20) - relativedelta(months=1)
print(last_month)
Using arrow:
import arrow # pip install arrow
d = arrow.now()
last_month = d.shift(months=-1).replace(day=20).datetime.date()
print(last_month)

Compare datetime field with date in django orm

Code :
start_date = '2017-02-03'
OutputData = Entity.objects.filter(created_on__year=start_date.year,
created_on__month=start_date.month,created_on__day=start_date.day).count()
I have data on that date but still I get 0 count in output and I am not getting why.
Please tell me what I am doing wrong.
convert start_date into python date object then do the filtering.
Example
from datetime import datetime
[1]:start_date = '2017-02-03'
[2]:start_date = datetime.strptime(startdate, '%Y-%m-%d')
[3]:start_date.year ## 2017
OutputData = Entity.objects.filter(created_on__year=start_date.year,
created_on__month=start_date.month,created_on__day=start_date.day).count()

Query Unix time by day in Python

I currently store a timestamp like this:
datetime = int(time.mktime(_scheduled_datetime.timetuple()))
> 1172969203.1
I need to then find all objects with a datetime of now().
Unfortunately, my application does not allow me to query ranges, only whole values. Is it possible to store only the days part of a timestamp i.e. 01/01/2016 So I could get all datetime values for today().
you can try:
import time
import datetime
timestamp = int(time.time())
# date timestamp
print int(
time.mktime(
datetime.date.fromtimestamp(timestamp).timetuple()
)
)
# iso format date string
print datetime.date.fromtimestamp(timestamp).isoformat()

Categories