How to Extract Dates in DateRangeField in Django - python

I'm trying to extract the dates in the DateRange field in django. I'm trying to see if a date is within the range of that DateRange but I'm unable to extract the dates in DateRange. Here's a sample:
'date_range': DateRange(datetime.date(2017, 2, 17), datetime.date(2017, 2, 18), '[)')
So I'm trying to get the first date and the second date and check if a certain date is within that range of DateRange.
How do I do that? Thanks!

You can retrieve the range values through .upper and .lower properties. E.g., my_object.date_range.upper.

if you want to check that a whether a particular date is in a date range or not you can compare the dates
from datetime import date
>>> start = date(2017, 02, 1)
>>> end = date(2017, 02, 28)
>>> curr = date.today()
>>> curr >= start and curr <= end
True

Related

find start and end date of previous month from current date in python

I need to find the start and end date of the previous month from the current date.
If the current date is 03-Feb-2021
The start date should be 01-Jan-2021 and the end date should be 31-Jan-2021.
how to achieve this as each month have a different number of days? Do we have any function in datetime to achieve this?
>>> from datetime import date, timedelta
>>> this_first = date.today().replace(day=1)
>>> prev_last = this_first - timedelta(days=1)
>>> prev_first = prev_last.replace(day=1)
>>> prev_first, prev_last
(datetime.date(2021, 1, 1), datetime.date(2021, 1, 31))
Format if/as needed.
first date will always be the 1st
# month_date = (datetime.now() - timedelta(days=20))
month_date = datetime.now().replace(day= monthrange(month_date.year,month_date.month - 1)[1]).strftime("%Y/%m/%d")
start_date = month_date.strftime("%Y/%m/01")
end_date = month_date.replace(day= monthrange(month_date.year,month_date.month)[1]).strftime("%Y/%m/%d")
imports are
from datetime import datetime, timedelta
from calendar import monthrange
you can add one condition for january so it will take december. If have any problem with that just add comment I will add that too.

How to get date using 3 date components with varied data types

I have three variables:
week_no = 2
day = 'Fri'
year = 2021
I need to locate the date by using these variables and output as a datetime.date object.
Thanks.
Following code:
datetime.datetime.strptime(f'{week_no} {day} {year}', '%U %a %Y')
Return following result:
datetime.datetime(2021, 1, 15, 0, 0)
You probably want to use datetime.date.fromisocalendar, though this is only available in Python 3.8+.
Return a date corresponding to the ISO calendar date specified by year, week and day. This is the inverse of the function date.isocalendar().
date.fromisocalendar(year, week, day)
The day is specified as an integer between 1 and 7.
>>> import datetime
>>> datetime.date.fromisocalendar(2021, 2, 5)
datetime.date(2021, 1, 15)

Generate a random list of n dates in the iso 8601 format within a range in Python

I want to generate a random list of dates in the iso8601 format within the range from 2019-01-01 to 2019-12-31 n times.
from datetime import date
start_date = date(2019,1,1)
end_date = date(2019,12,31)
Other threads I've looked at simply give the list of all dates within that range, but that's not what I need. I also need the dates to be in the iso8601 format. What is the best way to achieve this?
You can use random.sample to sample without replacement or random.choices to sample with replacement after generating a list of all the dates in the range.
If you don't want to store the list you could also generate N random numbers from 1 through 365, then convert those to the appropriate dates.
import random
from datetime import date, timedelta
end_date = date(2019, 12, 31)
current_date = date(2019, 1, 1)
n = 3
step = timedelta(days=1)
dates = [current_date]
while current_date != end_date:
current_date += step
dates.append(current_date)
random_dates = random.choices(dates, k=n)
print([d.isoformat() for d in random_dates])
You can do something like this
import datetime
import random
# startdate
start_date = datetime.date(2019, 1, 1)
# enddate
end_date = datetime.date(2019, 12, 31)
time_between_dates = end_date - start_date
days_between_dates = time_between_dates.days
#workload in days
random.seed(a=None)
random_number_of_days = random.randrange(days_between_dates)
random_date = start_date + datetime.timedelta(days=random_number_of_days)
print(str(random_date))
Which gave the following result when I ran it
2019-06-07
A similar question has been asked here
Python - Generate random dates to create Gantt sequenced tasks?
Most of the code is from there except the last loop
I create a dataframe with an datetimeindex with two iso8601 date values. I then resample the dataframe index to every 30Minute intervals then randomly choose 3 items from the dataframe.
df=pd.DataFrame({'timestamp':['2019-01-01T00:00:00.000Z','2019-12-31T23:59:59.300Z']})
df['timestamp']=df['timestamp'].apply(lambda timestamp: datetime.strptime(timestamp, '%Y-%m-%dT%H:%M:%S.%f%z'))
print(df['timestamp'])
df=df.set_index('timestamp')
dates = df.resample('30Min').max().dropna()
#print(dates)
random_dates = random.choices(dates.index, k=3)
print(random_dates)
output:
[Timestamp('2019-08-29 16:30:00+0000', tz='UTC', freq='30T'), Timestamp('2019-11-09 03:30:00+0000', tz='UTC', freq='30T'), Timestamp('2019-08-02 12:00:00+0000', tz='UTC', freq='30T')]

Get all months and years in a range

I am writing a django application where I have records stored on the basis of datetimefield.
first_record = MyModel.objects.filter().order_by('-added').first()
first_record = (first_record.added.month, first_record.added.year)
last_record = MyModel.objects.filter().order_by('-added').first()
last_record = (last_record.added.month, last_record.added.year)
Now I want to make a list of all months/year between the first record and last record. A rough idea is:
for i in range(first_record, last_record):
# do something
Where the range function is supposed to give me a list to iterate over which looks like this:
[('01','2018'),('02','2018'),('03','2018'),....,('11','2020'),('12','2020')]
Any ideas how do I do that?
Also is (last_record.added.month, last_record.added.year) the right way to get a tuple containing month and year. Note that I want months in the format 01 instead of 1 for first month for example.
I believe Django has a built-in function. You can do:
>>> Entry.objects.dates('pub_date', 'month')
[datetime.date(2005, 2, 1), datetime.date(2005, 3, 1)]
>>> Entry.objects.dates('pub_date', 'week')
[datetime.date(2005, 2, 14), datetime.date(2005, 3, 14)]
Which, translated into your code, will be something like
MyModel.objects.dates('added', 'month')
Documentation
You can do this by using dateutil.relativedelta
Here is the code
from dateutil.relativedelta import relativedelta
import datetime
result = []
today = datetime.date.today()
current = datetime.date(2010, 8, 1)
while current <= today:
result.append(current)
current += relativedelta(months=1)
Know more abou in
https://dateutil.readthedocs.io/en/latest/relativedelta.html

How to convert a list of dates into a list of strings

I am trying to have a list of dates printed out across a google spreadsheet, so far I have the following script, which works fine in getting a list of dates, but I need to know how to convert this list of dates into a list of strings..
def daterange(startdate, enddate):
r = (enddate+datetime.timedelta(days=1)-startdate).days
return [startdate+datetime.timedelta(days=i) for i in range(r)]
startdate = datetime.date(2018, 11, 19)
enddate = datetime.date(2018,11,25)
datelist = daterange(startdate, enddate)
print ([str(date) for date in datelist])
I would have thought that 'str(date) would have accomplished this but it is still a list of dates..I am not an experienced programmed so please explain simply.
** EDIT
I realized my error.. It was printing a string fine, but as far as I can tell I need the dates to be stored as strings first, and then to update the spreadsheet with a list of strings.. I actually didn't need to use the print function at all (and I haven't with other lists of strings I've worked with on this project)Can anyone show me how to convert and store these dates as strings?
This line is ok:
print ([str(date) for date in datelist])
These are other ways you could print out the datelist:
print ([date.strftime('%Y-%m-%d') for date in datelist])
print ([str(date) for date in datelist])
print (["%s" % date for date in datelist])
print ([date for date in datelist])
print (datelist)
The last two examples results in this output:
[datetime.date(2018, 11, 19), datetime.date(2018, 11, 20), datetime.date(2018, 11, 21), datetime.date(2018, 11, 22), datetime.date(2018, 11, 23), datetime.date(2018, 11, 24), datetime.date(2018, 11, 25)]
Take a look at https://docs.python.org/2/library/datetime.html#strftime-strptime-behavior
With this you can convert a date to your desired string format. Loop over your list again and turn them all into string variants.
for date in datelist:
print(data.strftime("%B %d, %Y"))

Categories