Python - Calendar / Date Library for Arithmetic Date Operations - python

This is for Python:
I need a library that is able to do arithmetic operations on dates while taking into account the duration of a month and or year.
For example, say I add a value of "1 day" to 3/31/2020, the result of should return:
1 + 3/31/2020 = 4/1/2020.
I also would need to be able to convert this to datetime format, and extract day, year and month.
Does a library like this exist?

import datetime
tday = datetime.date.today() # create today
print("Today:", tday)
""" create one week time duration """
oneWeek = datetime.timedelta(days=7)
""" create 1 day and 1440 minutes of time duraiton """
eightDays = datetime.timedelta(days=7, minutes=1440)
print("A week later than today:", tday + oneWeek) # print today +7 days
And the output to this code snippet is:
Today: 2020-03-25
A week later than today: 2020-04-01
>>>
As you see, it takes month overflows into account and turns March to April. datetime module has lots of things, I don't know all its attributes well and haven't used for a long time. However, I believe you can find nice documentation or tutorials on the web.
You definitely can create any specific date(there should be some constraints though) instead of today by supplying day, month and year info. I just don't remember how to do it.

Related

How can I get the year, month, and day from a Deephaven DateTime in Python?

I have a Deephaven DateTime in the New York (US-East) timezone and I'd like to get the year, month, and day (of the month) numbers from it as integers in Python.
Deephaven's time module has these utilities. You may have used it to create a Deephaven DateTime in the first place.
from deephaven import time as dhtu
timestamp = dhtu.to_datetime("2022-04-01T12:00:00 NY")
The following three methods will give you what you're looking for:
year - Gets the year
month_of_year - Gets the month
day_of_month - Gets the day of the month
All three methods will give you what you want based on the DateTime itself and your preferred time zone.
tz_ny = dhtu.TimeZone.NY
year = dhtu.year(timestamp, tz_ny)
month = dhtu.month_of_year(timestamp, tz_ny)
day = dhtu.day_of_month(timestamp, tz_ny)

How to retrieve previous NYSE trading day in Pandas?

I'm trying to get the previous trading day in relation to a given trading day. To start I am simply trying to make a function which returns the previous business day when given a date, like so:
import datetime
def get_previous_trading_day(day):
day = pd.to_datetime(day)
previous_trading_day = day - datetime.timedelta(days=1)
return previous_trading_day
But when I call my function and print the current vs previous date, the previous date is not the previous day:
2021-05-01 curr
1885-02-22 00:00:00 prev
How do I make this work?
If you change the calculation to use pd.tseries.offsets.BDay instead, you will get the previous business day (instead of the day before). I realise this will not work for bank holidays where no trading occurs. Your function works well when I try it for returning the previous day's date.
def get_previous_trading_day(day):
day = pd.to_datetime(day)
previous_trading_day = day - pd.tseries.offsets.BDay(1)
return previous_trading_day
Calling the function for tomorrow's date will return Friday's date:
get_previous_trading_day("2022-05-16")
#Out: Timestamp('2022-05-13 00:00:00')
For your returned date, you may have put a date format that was not read correctly by the pd.to_datetime. If you require a specific format, add the kwarg format= to this.

Work out if date is in current week python

I'm trying to write a bit of code to check if a document has been updated this week, and if not to read in the data and update it. I need to be able to check if the last modified date/time of the document occurred in this week or not (Monday-Sunday).
I know this code gives me the last modified time of the file as a float of secconds since the epoch:
os.path.getmtime('path')
And I know I can use time.ctime to get that as a string date:
time.ctime(os.path.getmtime('path'))
But I'm not sure how to check if that date was in the current week. I also don't know if its easier to convert to a datetime object rather than ctime for this?
you can use datetime.isocalendar and compare the week attribute, basicallly
import os
from datetime import datetime
t_file = datetime.fromtimestamp(os.path.getmtime(filepath))
t_now = datetime.now()
print(t_file.isocalendar().week == t_now.isocalendar().week)
# or print(t_file.isocalendar()[1]== t_now.isocalendar()[1])
# to compare the year as well, use e.g.
print(t_file.isocalendar()[:2] == t_now.isocalendar()[:2])
The ISO year consists of 52 or 53 full weeks, and where a week starts on a Monday and ends on a Sunday. The first week of an ISO year is the first (Gregorian) calendar week of a year containing a Thursday. This is called week number 1, and the ISO year of that Thursday is the same as its Gregorian year.

Date selection using Selenium

So I'm building a program that extracts data from several different websites that will display all our business data on a dashboard.
I've managed to get to the point where I can extract the data I need, and have it set up to select todays data, previous week and month to date by importing datetime, and for the example of previous week the following:
date = datetime.date.today()
yesterday = (date - datetime.timedelta(days = 1)).strftime('%d')
lastWeek = (date - datetime.timedelta(days = 7)).strftime('%d')
today = date.strftime('%d')
Then just using the find element function:
browser.find_element_by_link_text(lastWeek).click()
However I'm running into problems at the beginning of the month, where I can't subtract 7 as it would take me into negative numbers and wouldn't go to the previous months date as each month has different days etc.
Is there any way of getting around this?
TIA

accept multiple date arguments in a function

Bonjour!
I want to write program to calculate 28 day cycle for when rent is due, but if atthe end of year i calculate the no of days i paid the rent late , i wish to total those days and calculate them based on paid dates in my code.
the question is how to insert multiplepaidDates for the whole year i.e. 12 for calculating the days i paid late? how to insert multiple arguments for it in the function datespan?
link: How to iterate over a timespan after days, hours, weeks and months in Python?
help appreciated.
Merci.
from datetime import date, datetime, timedelta
def datespan(startDate, endDate, paidDate,delta=timedelta(days=1)):
currentDate = startDate
while currentDate < endDate:
yield currentDate
currentDate += delta
dl = paidDate - currentDate
print (dl)
for day in datespan(date(2015,3,12 ), date(2015,12,31), date((2015,4,15), date(2015,5,14)),
delta=timedelta(days=28)):
print (day)
It looks like you want to use varargs. This is possible with python. You would change your method signature to be:
def datespan(startDate, endDate, delta, *paidDates)
This will allow you to pass in as many paidDates arguments as you want. Note that you will not be able to use the default arg for delta anymore.
datespan(date(2015,3,12), date(2015,12,31), timedelta(days=28), date(2015,4,15), date(2015,5,14))
should work fine in this case. You will also need to modify your function to handle a sequence of paidDates as opposed to just one coming in as an argument.

Categories