Function returning the following days and months in python3 - python-3.x

I am writing a webscraper and the URL is based on the dates:
checkin_month=2&checkin_monthday=21&checkin_year=2020&checkout_month=2&checkout_monthday=22
There are 4 variables: checkin day and month, and checkout day and month. Checkout day will be always be = checkin day + 1. But when the newmonth is ending, checkout day is 1 and checkout month = checkin month +1.
Is there any function or library I can use to somehow implement it or do I have to write my own code to solve this?

You can use:
from datetime import timedelta
then :
yourDate += timedelta(days=1)
This previous code increments your date by one day. But, to increment the date, your date must be of type datetime.
Below, the documentation of thhis class.
class datetime.timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0)
You can see a tutorial to manipulate date here : https://www.dataquest.io/blog/python-datetime-tutorial/

Related

Get dynamic dates for URL on any day of the month

I'm scraping a website with requests. The URL requires dynamic dates so i'm generating the dates to use with the following variables:
stmDt = (pd.to_datetime('today').date()+ pd.offsets.MonthBegin(-1)).strftime('%d-%b-%Y')
todDt = (pd.to_datetime('today').date()).strftime('%d-%b-%Y')
snmDt = (pd.to_datetime('today').date()+ pd.offsets.MonthBegin(1)).strftime('%d-%b-%Y')
enmDt = (pd.to_datetime('today').date()+ pd.offsets.MonthEnd(2)).strftime('%d-%b-%Y')
For this example, i'm running this script on 11/30/2022 (last day of the month).
stmDt = start this month date (first day of month on which we run script - 11/1/2022)
todDt = today (11/30/2022)
snmDt = start next month (12/1/2022)
enmDt = end next month (12/31/2022)
The date variables are correct most of the time, but it appears (for november run dates):
On the first day of the month: stmDt shows the first day of the
previous month (10/1/22)
On the last day of the month: enmDt shows the last day two months
from now (1/31/23)
How can I tweak these so they always give me the correct dates? Happy to use other packages to accomplish etc
Thanks
You can do this using dateutil.relativedelta like this:
from datetime import datetime
from dateutil.relativedelta import relativedelta
today = datetime.now()
stmDt = today.replace(day=1).strftime('%d-%b-%Y')
todDt = today.strftime('%d-%b-%Y')
snmDt = (today + relativedelta(months=1)).replace(day=1).strftime('%d-%b-%Y')
enmDt = ((today + relativedelta(months=2)).replace(day=1) - relativedelta(days=1)).strftime('%d-%b-%Y')

How to get / output all days in the current week in Automation Anywhere?

I'm attempting to output all days within the current week. e.g. for this week, show all days, 05/12/2019 through 05/18/2019 only. when the bot is executed next week, only show days 05/19/2019 through 05/25/2019. My current logic outputs the days for this week, but come tomorrow, the dates for this week will be thrown off. Please see the following
...could I get some help with this please?
Using VBS
I would do this using a VBS script, using Run Script command.
The default week start is Sunday you can change it check: https://www.w3schools.com/asp/func_weekday.asp
Pass the day you that you want as a parameter from 0 to 6, and get the data as a return value.
DayNumber: 0 = Sunday ..... 6 = Saturday
InputDate = Date
DayNumber = WScript.Arguments.Item(0)
Result = DateAdd("d", DayNumber - WeekDay(InputDate, 2), InputDate)
WScript.StdOut.Write(Result)
'MsgBox(Result)
Using MetaBot
Metabot Link: Change Date and Time Format
You will have to run the following logic in sequence.
Input: DayNumber: 0 = Sunday ..... 6 = Saturday
Using DayOfWeek Logic, Get the Day of the week and assign it to
WeekDay variable, it will return the name, not the number, and the input will be Date.
Using IF conditions convert the name of
the day to number, start from 0 to 6 as your first day in the week,
which is Sunday, and using variable operation assigns the value to
NumWeekDay variable.
Using variable operation, Get the offset by subtracting DayNumber, the day you want minus NumWeekDay,
and assign the value to Offset variable.
Using AddDays, Input
the date and the offset, and you will get the date of the day that you want.

Django date filter - find a date in-between

I'm attempting to create a query that returns an event if it runs at any point in a given period of time between 2 dates.
model:
class MyModel(models.Model):
start_date = models.DateField(auto_now=False, blank=True, null=True, verbose_name="Start date")
hd_end_date = models.DateField(blank=True, default=None, null=True, verbose_name="End date")
Current code to try and filter:
import calendar
max_day = calendar.monthrange(year, month)[1]
start = "{}-{}-01".format(year, month)
end = "{}-{}-{}".format(year, month, max_day)
# If the event starts in the month, or if it ends in the month
filter.append(Q(start_date__range=[start, end]) |
Q(hd_end_date__range=[start, end]))
My models have a start_date and an end_date (hd_end_date). This logic appeared to work as intended at first. However there is problem and I know what is, just not how to solve it.
For example if my event model starts in December and finishes in February the above code would return an event for December and in February but it wouldn't return one for January as it neither starts or ends in that month. How can I adjust this code so that it would return an event that run over multiple months.
Appears I was over thinking it, and resolved the issue by simplifying.
filter.append(Q(start_date__month__lte=month, hd_end_date__month__gte=month))
I realised that I could just look at the month and didn't need to range the dates, as all I wanted to know is that the event ran on that month between it's start and end date.

How can I convert from a datetime to a weekday of the month constant?

What I want to do is figure out what X of the month this is, and returning the relative delta constant for it (Su Mo Tu...). I have found many examples of jumping to a specific day of the month (1). For instance today is the 3rd Tuesday of December and I can get to it by doing this: + relativedelta(month=12, day=1, weekday=TU(3))) but what I want to do is the opposite:
Put in today's date and subtract the first of the month and get something like TU(3) or if it were the 4th wednesday to get: WE(4)
My ultimate goal is to then be able to transfer this constant to a different month or timedelta object and find the equivalent 3rd Tuesday, or 4th Wednesday, etc...
This is a solution that I have come up with, maybe you'll find it less complicated.
It also seems to be about 4 times faster, which if you process a lot of dates can make a difference.
from datetime import *
from dateutil.relativedelta import *
def weekDayOfTheMonth(xdate):
daylist = [MO,TU,WE,TH,FR,SA,SU]
weekday = xdate.weekday()
firstDayOfTheMonth = datetime(xdate.year, xdate.month, 1)
interval = (weekday + 7 - firstDayOfTheMonth.weekday() ) % 7
firstOfThisWeekDay = datetime(xdate.year, xdate.month, 1 + interval)
n = ((xdate.day - firstOfThisWeekDay.day) / 7) + 1
return daylist[weekday](n)
print(weekDayOfTheMonth(datetime.today()))
print(weekDayOfTheMonth(datetime(2018,11,24)))
Basically what happens is that:
I find what day of the week is the first day of given month.
Based on that information I can easily calculate first day of any given weekday in given month.
Then I can even more easily calculate that for example 18th of December 2018 is third Tuesday of this month.
Ok I found a way using rrule to create a list of days in the month that share the current weekday up until today, then length of this list becomes the Nth. Than I use a list as a lookup table for the weekday constants. Not tested to see if this will work for every day of the month but this is a start.
from datetime import *; from dateutil.relativedelta import *
from dateutil.rrule import rrule, WEEKLY
import calendar
def dayofthemonth(xdate):
daylist = [MO,TU,WE,TH,FR,SA,SU]
thisweekday = daylist[xdate.weekday()]
thisdaylist = list(rrule(freq=WEEKLY, dtstart=xdate+relativedelta(day=1), until=xdate, byweekday=xdate.weekday()))
return thisweekday(len(thisdaylist))
print(dayofthemonth(datetime.today())) #correctly returns TU(+3) for 2018, 12, 18

How to count a leap year, when calculating dates in Groovy

I need to plus some days for the date. When I use this code, I miss a leap year. How not to miss it?
import java.time.LocalDate
LocalDate dob = LocalDate.of(1900, 1, 1).plusDays(40176)

Resources