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()
Related
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
From what I've seen this should be working even if it's not the prettiest. I've tried plenty of things but doesn't seem to work with anything and best I've been able to do is change the error message lol.
try:
date = dt.datetime.now()
d1 = date - timedelta(days=1)
d1.strftime('%Y%m%d')
url = 'http://regsho.finra.org/FNQCshvol' + d1 + '.txt'
Try the following:
from datetime import timedelta
import datetime as dt
date = dt.datetime.now()
d1 = date - timedelta(days=1)
d1 = d1.strftime('%Y%m%d') # I changed this line
url = 'http://regsho.finra.org/FNQCshvol' + d1 + '.txt'
strftime() returns the string, it does not convert the date itself to a string.
I modified your code a little. There were a couple of mistake in it and it wasn't running.
The main problem you were running into is you were trying to concatenate a string with a datetime object. You applied the strftime correctly but you didn't save the string. That string you can concatenate with another string.
import datetime as dt
date = dt.datetime.now()
d1 = date - dt.timedelta(days=1)
d1_string = d1.strftime('%Y%m%d')
url = 'http://regsho.finra.org/FNQCshvol{timestamp}.txt'.format(timestamp=d1_string)
In your code you don't assign result of datetime.strftime() to a variable. Solution is simple:
from datetime import datetime, timedelta
current_date = datetime.now() # store current date and time
required_date = current_date - timedelta(days=1) # substitute 1 day
str_date = required_date.strftime('%Y%m%d') # apply formatting
url = f'http://regsho.finra.org/FNQCshvol{str_date}.txt'
You can also do it in one line (which makes code much less readable):
url = f"http://regsho.finra.org/FNQCshvol{(datetime.now() - timedelta(days=1)).strftime('%Y%m%d')}.txt"
I need to amend an existing python sript which extracts data from previous day to extract data for last two weeks like biweekly data. Please advise how I can twik to get the date range in the variable
def parse_gov():
reject_patterns = generate_reject_patterns()
today_str = date.today().strftime('%Y.%m.%d')
yesterday =
yesterday_str = yesterday.strftime('%Y.%m.%d')
query_date = date.today()
So need to get the date range in yesterday variable
You can use timedelta to do so. for example,
import datetime
today = datetime.date.today()
yesterday = today - datetime.timedelta(days=1)
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
I have the following string format (Python 3.6):
'2018-11-19T10:04:57.426872'
I get it as a parameter to my script.
I want to get the date as 'YYYY-MM-DD' and time as 'HH:MM'
I tried to convert it with:
from datetime import datetime
if __name__ == '__main__':
start_timestamp = sys.argv[1]
start_date = datetime.strptime(sys.argv[1], '%Y-%m-%d')
start_time = datetime.strptime(sys.argv[1], '%H:%M')
But this gives:
ValueError: unconverted data remains: T10:04:57.426872
In the above example I want to see:
start_date = '2018-11-19'
start_time = '10:04'
Since the date seems to be in ISO-Format, a simple
start = datetime.datetime.fromisoformat(text)
will parse it correctly. From there you can get your date and time with
start_date = start.strftime("%Y-%m-%d")
start_time = start.strftime("%H:%M")
Edit:
For Python < 3.7, you can use this format:
start = datetime.datetime.strptime(text, "%Y-%m-%dT%H:%M:%S.%f")
For the "duplicate" datetime confusion: I used import datetime. If you use from datetime import datetime, you can get rid of the additional datetime.
Try this:We have one of the best package for parsing dates called dateutil.
from dateutil import parser
date1='2018-11-19T10:04:57.426872'
print 'Start_date:',parser.parse(date1).strftime("%Y-%m-%d")
print 'Start_time:',parser.parse(date1).strftime("%H:%M")
Result:Start_date:2018-11-19
Start_time:10:04
You need to parse the entire string into one datetime object and then extract your required values from that.
dt = datetime.datetime.strptime('2018-11-19T10:04:57.426872', '%Y-%m-%dT%H:%M:%S.%f')
d = dt.date()
t = dt.time()
print(d.strftime('%Y-%m-%d'))
print(t.strftime('%H:%M'))
Which outputs:
2018-11-19
10:04