How can I compare an input with the month from datetime library? - python-3.x

I am doing a program in pyhon(3.10.1) in which i need to compare an input, in this case the number of a month (for example 05 for may) with the local current time.
from datetime import datetime
month=int(input("insert the number of a month: "))
dt_obj = datetime.now()
dt_frt = dt_obj.strftime("%m")
print(dt_frt)
if (month==dt_frt):
print("the month you selected is equal to the current month")
Then it stops at printing the current month, but does not do what the two last lines say, and it does not give any error. can anybody help me? Thanks.

I think you're comparing int with str, that's why the if condition isn't true. To fix this, you can remove the int(input(...)) or add a str(...) around your dt_frt
You can also get the month with just date.month (doc)

Related

Convert Excel date number to datetime in Python

I want to covert a column with Excel date numbers (float) to datetime, below is the function I am trying to use:
import datetime
datetime.datetime.fromtimestamp(42029.0).strftime('%Y-%m-%d')
Bu the result I got is: '1970-01-01',I don't think it is right, I must missing a constant which should be added to the variable, because in the excel the number 42029.0 represents date: 1/25/2015.
Can anyone please advise how to improve the code?
datetime.fromtimestamp() follows the unix convention and expects seconds since '1970-01-01'. The Excel date number for '1970-01-01' is 25569, so you have to subtract this number from your given date number and multiply the result, which is in days, with 86400 (seconds per day):
datetime.datetime.fromtimestamp(
(42029.0 - 25569) * 86400).strftime('%Y-%m-%d')
'2015-01-25'

Check if a date belongs to a given month and year in python

Is there a built-in python function where I would check a given date if it belongs to a month and year. For example I would like to check if a date 05/15/2019 belongs to 05/2019 month and year. I've created a function where I split the date then match its month and year to 05/2019. I would just like to know if there is a built-in function
Pasting a function, which we use in our project, if helpful
def is_in_month(test_date, month_start_end={}):
"""
Check to see if the date falls within the last month. Expects a dict with
start and end properties.
"""
if not month_start_end.get("start") or not month_start_end.get("end"):
raise ValueError("Need a dict. with start and end")
if month_start_end.get("start").tzinfo is not None and month_start_end.get("start").tzinfo.utcoffset(month_start_end.get("start")) is not None:
return month_start_end.get("start") <= pytz.UTC.localize(test_date) <= month_start_end.get("end")
return month_start_end.get("start") <= test_date <= month_start_end.get("end")

Python3 Count Number of Week Days Ignoring Holidays

Testing one of my scripts it appears that Numpy busday_count includes Labor Day (September 2nd). Is there a way to disable the holidays?
print (np.busday_count('2019-08-31', '2019-09-02'))
Result = 0, but 9/2/2019 is clearly Labor Day and a Monday.
print (np.busday_count('2019-08-31', '2019-09-03'))
Result = 1, but it should be 2. As far as I know the formula excludes the first date but includes the second date. I also tried:
print (np.busday_count('2019-08-31', '2019-09-02', holidays=[]))
Result still = 0 despite attempt to clear any holidays. What am I missing?
As so often, the answer lies with the documentation and Python's love for half-open intervals:
Counts the number of valid days between begindates and enddates, not including the day of enddates.

Send an email based on the date in a CSV column

I am looking to read data from a column in my CSV file.
All of the data in this column are dates. (DD/MM/YYYY).
I want my program to read the Dates column, and if the date is within 3 days of the current date, I want to add variables to all of the values in that row.
Ex.
Date,Name,LaterDate
1/1/19,John Smith, 2/21/19
If I run my program on 2/19/2019, I want an email sent that says "John Smith's case is closing on "2/21/2019".
I understand how to send an email. The part that I get stuck on is:
Reading the CSV column specifically.
If the date is within 3 days,
Assign variables to the values in the ROW,
Use those variables to send a custom email.
I see a lot of "Use Pandas" but I might need the individual steps broken down.
Thank you.
First things first, you need to read all the values of the csv file and store it in a variable (old_df). Then you need to save all the dates in the Series (dates). Next we create an empty DataFrame with the same columns. From here we create a simple for loop for each date in dates and it's index i. Turn date into a datetime object from the datetime library. Then we subtract amount of days between the current date and date. Take the absolute value of days so we always get a positive amount of days. Then add the index of that particular date in old_df to new_df.
import pandas as pd
from datetime import datetime
old_df = pd.read_csv('example.csv')
dates = old_df['LaterDate']
new_df = pd.DataFrame(columns=['Date', 'Name', 'LaterDate'])
for i, date in enumerate(dates):
date = datetime.strptime(date, '%m/%d/%y')
days = (datetime.now() - date).days
if abs(days) <= 3:
new_df = new_df.append(old_df.loc[i, :])
print(new_df)

Excel split cost figure between months with partial dates

I have a list of cost figures with start dates and end dates which I need to split between months, I have searched for the solution to this problem but cannot seem to find one that will work with partial months i.e.( startdate:01/01/2015 enddate: 15/04/2015 cost:10000) which would leave figures like Jan:2857, Feb:2857, Mar:2857, Apr:1429.
I have been trying to modify this example: http://www.excel-university.com/excel-formula-to-allocate-an-amount-into-monthly-columns/ but having no luck getting the partial months working.
Any suggestions or help would be most welcome. Thanks in Advance
if you calculate it on daily basis, would it be ok? the result would be:
01.01.2015 01.02.2015 01.03.2015 15.04.2015
2.857,14 2.857,14 2.857,14 1.428,57
your daily amount is:
=10.000/(DAYS360(startdate;enddate;TRUE)+1)
(be carefull of true and false argument)
under the dates or instead of 2.857,14 etc. insert the formula:
=IF(DAY("your date")>1;DAY("your date");30) * daily amount
This formula assumes that you want to have 30 days in each month:
=IF(DAY(01.01.2015)>1;DAY(01.01.2015);30)
result = 30
=IF(DAY(15.04.2015)>1;DAY(15.04.2015);30)
result = 15
so if months begins with a date different from the 1st it will give you the number of days.
if you want to match months with your startdate and enddate (if i understood your comment correctly), you could do:
=IF(OR(
AND(MONTH(startdate)=MONTH(your date);YEAR(startdate)=YEAR(your date));
AND(MONTH(enddate)=MONTH(your date);YEAR(enddate)=YEAR(your date))
);"match";"no match")
by this you make sure that month and year correspond.
If you want to get the number of days in a month automatically, you could use:
=DAY(DATE(YEAR("your date");MONTH("your date")+1;1)-1)
but this does not assume anymore 30 days, you can change it with if statement
I hope this helps,
Best - AB

Resources