This question already has answers here:
How do I check if it's Monday to Friday and the time is between 10 AM to 3 PM?
(3 answers)
Closed 3 years ago.
I'm finding this quite difficult and I'm not too sure which imports to use. Either way:
from datetime import datetime
from datetime import timedelta
from datetime import date
import holidays
def isTradingDay(theDate):
isWeekday = False
isBankHoliday = False
# Select country
holidayDates = holidays.UnitedKingdom()
#Check WeekDay and Bank Holiday status
if(datetime.today().weekday() < 6):
isWeekday = True
if(theDate in holidayDates):
isBankHoliday = True
#Return True if trading day
if(isWeekday == False and isBankHoliday == False):
return True
else:
return False
The issue lies with datetime.today().weekday() < 6 I want to use this line to check if the value theDate is a weekday. But I can't find the correct way of checking theDate.
theDate format is: (datetime.today() - timedelta(days = offset)).strftime('%d-%m-%Y')
Are there options that can be worked into the above?
If theDate is the datetime object, you can use .weekday() function too:
if(theDate.weekday() < 6):
If it is a string, you should first convert it to datetime with strptime:
dtime = datetime.strptime(theDate, '%Y-%m-%d')
'%Y-%m-%d' string depends on your string format of theDate
Related
This question already has answers here:
How to subtract a day from a date?
(7 answers)
Closed 2 years ago.
I am trying to identify records that expire within 1 year of today's date. This is the code I have and it doesn't work because I can't add or subtract integers from dates. Can someone assist? I know this is simple.
from datetime import date
today = date.today()
mask = (df['[PCW]Contract (Expiration Date)'] <= today + 365)
You need to use time deltas.
from datetime import timedelta
one_year = timedelta(days=365)
mask = (df['[PCW]Contract (Expiration Date)'] <= today + one_year)
Assuming you are using datetime objects in your dataframe.
UPDATE
import pandas as pd
import numpy as np
df = pd.DataFrame({'[PCW]Contract (Expiration Date)' :["2020-01-21T02:37:21", '2021-01-21T02:37:21', '2022-01-21T02:37:21']})
s = pd.to_datetime(df['[PCW]Contract (Expiration Date)'])
one_year = np.timedelta64(365,'D')
today = np.datetime64('today')
mask = s <= today + one_year
mask
Output
0 True
1 True
2 False
Name: [PCW]Contract (Expiration Date), dtype: bool
This question already has answers here:
Add 1 day to my date in Python [duplicate]
(1 answer)
Adding days to a date in Python
(16 answers)
Closed 2 years ago.
I'm trying to add one day to custom date(in string). Time format is dd/mm/yyyy
Sample input:
'02/11/2020'
Output:
'03/11/2020'
from datetime import datetime, timedelta
date = '02/11/2020'
old = datetime.strptime(date, "%d/%m/%Y")
new = old + timedelta(days=1)
new_date = new.strftime("%d/%m/%Y")
print(new_date) # '03/11/2020'
You can use the datetime module
from datetime import datetime, timedelta
start = datetime.strptime("%d/%m/%Y", "02/11/2020")
end = start + datetime.timedelta(days = 1)
This question already has answers here:
Find Monday's date with Python
(8 answers)
How do I get the day of week given a date?
(30 answers)
Closed 5 years ago.
How would I write a statement that says:
If today is Monday, then run this function.
My thoughts are:
if datetime.now().day == Monday:
run_report()
But I know this is not the right way to do it. How would I properly do this?
You can use date.weekday() like this:
from datetime import date
# If today is Monday (aka 0 of 6), then run the report
if date.today().weekday() == 0:
run_report()
import datetime as dt
dt.date.today().isoweekday() == 1 # 1 = Monday, 2 = Tues, etc.
Both datetime.date and datetime.datetime
objects have a today method that return respectively a Date and a Datetime object.
Which both have a weekday and isoweekday methods.
weekday count from Monday = 0, while isoweekday count from Monday = 1:
from datetime import date, datetime
if date.today().weekday() == 0:
# it is Monday
if datetime.today().isoweekday() == 1:
# it is Monday
See documentation
This question already has answers here:
Convert string "Jun 1 2005 1:33PM" into datetime
(26 answers)
Closed 7 years ago.
I have a raw input from the user such as "2015-01-30"...for the query I am using, the date has to be inputed as a string as such "yyyy-mm-dd".
I would like to increment the date by 1 month at end of my loop s.t "2015-01-30" becomes "2015-02-27" (ideally the last business day of the next month). I was hoping someone could help me; I am using PYTHON, the reason I want to convert to datetime is I found a function to add 1 month.
Ideally my two questions to be answered are (in Python):
1) how to convert string "yyyy-mm-dd" into a python datetime and convert back into string after applying a timedelta function
2) AND/or how to add 1 month to string "yyyy-mm-dd"
Maybe these examples will help you get an idea:
from dateutil.relativedelta import relativedelta
import datetime
date1 = datetime.datetime.strptime("2015-01-30", "%Y-%m-%d").strftime("%d-%m-%Y")
print(date1)
today = datetime.date.today()
print(today)
addMonths = relativedelta(months=3)
future = today + addMonths
print(future)
If you import datetime it will give you more options in managing date and time variables. In my example above I have some example code that will show you how it works.
It is also very usefull if you would for example would like to add a x number of days, months or years to a certain date.
Edit:
To answer you question below this post I would suggest you to look at "calendar"
For example:
import calendar
january2012 = calendar.monthrange(2002,1)
print(january2012)
february2008 = calendar.monthrange(2008,2)
print(february2008)
This return you the first workday of the month, and the number of days of the month.
With that you can calculate what was the last workday of the month.
Here is more information about it: Link
Also have a loook here, looks what you might could use: Link
converting string 'yyyy-mm-dd' into datetime/date python
from datetime import date
date_string = '2015-01-30'
now = date(*map(int, date_string.split('-')))
# or now = datetime.strptime(date_string, '%Y-%m-%d').date()
the last business day of the next month
from datetime import timedelta
DAY = timedelta(1)
last_bday = (now.replace(day=1) + 2*31*DAY).replace(day=1) - DAY
while last_bday.weekday() > 4: # Sat, Sun
last_bday -= DAY
print(last_bday)
# -> 2015-02-27
It doesn't take into account holidays.
You can use a one-liner, that takes the datetime, adds a month (using a defined function), and converts back to a string:
x = add_months(datetime.datetime(*[int(item) for item in x.split('-')]), 1).strftime("%Y-%m-%d")
>>> import datetime, calendar
>>> x = "2015-01-30"
>>> x = add_months(datetime.datetime(*[int(item) for item in x.split('-')]), 1).strftime("%Y-%m-%d")
>>> x
'2015-02-28'
>>>
add_months:
def add_months(sourcedate,months):
month = sourcedate.month - 1 + months
year = sourcedate.year + month / 12
month = month % 12 + 1
day = min(sourcedate.day,calendar.monthrange(year,month)[1])
return datetime.date(year,month,day)
To convert a string of that format into a Python date object:
In [1]: import datetime
In [2]: t = "2015-01-30"
In [3]: d = datetime.date(*(int(s) for s in t.split('-')))
In [4]: d
Out[4]: datetime.date(2015, 1, 30)
To move forward to the last day of next month:
In [4]: d
Out[4]: datetime.date(2015, 1, 30)
In [5]: new_month = (d.month + 1) if d.month != 12 else 1
In [6]: new_year = d.year if d.month != 12 else d.year + 1
In [7]: import calendar
In [8]: new_day = calendar.monthrange(new_year, new_month)[1]
In [9]: d = d.replace(year=new_year,month=new_month,day=new_day)
In [10]: d
Out[10]: datetime.date(2015, 2, 28)
And this datetime.date object can be easily converted to a 'YYYY-MM-DD' string:
In [11]: str(d)
Out[11]: '2015-02-28'
EDIT:
To get the last business day (i.e. Monday-Friday) of the month:
In [8]: new_day = calendar.monthrange(new_year, new_month)[1]
In [9]: d = d.replace(year=new_year,month=new_month,day=new_day)
In [10]: day_of_the_week = d.isoweekday()
In [11]: if day_of_the_week > 5:
....: adj_new_day = new_day - (day_of_the_week - 5)
....: d = d.replace(day=adj_new_day)
....:
In [11]: d
Out[11]: datetime.date(2015, 2, 27)
I need help with a program.
How do I add 3 weeks (21 days) to any given date when the user can control the date?
The user will enter the date YYYY-MM-DD.
Below I'm trying to locate the hyphen and make sure there is only 2. This is what I have so far but all it does is repeat itself, can someone tell me where I went wrong ?:
date = raw_input("Enter date: ")
i = 0
while i <= len(date):
if date[i] != "-":
i = i + 1
print date
Now I'm picking out year, month, day. Is there an easier way to do this cause I need to account for the change months etc ?
year = date[0:4]
month = date[5:7]
day = date[9:11]
thanks
Use datetime module to the task. You create a datetime aware object and add 21 days timedelta object to it.
>>> import datetime
>>> u = datetime.datetime.strptime("2011-01-01","%Y-%m-%d")
>>> d = datetime.timedelta(days=21)
>>> t = u + d
>>> print(t)
2011-01-22 00:00:00
You can use a datetime.timedelta object to represent 3 weeks and then just add that to the datetime object that represents the user's input.
import datetime
date = raw_input("Enter date: ")
aDate = datetime.datetime.strptime(date,"%Y-%m-%d")
threeWeeks = datetime.timedelta(weeks = 3)
print aDate + threeWeeks
See http://docs.python.org/library/datetime.html#strftime-and-strptime-behavior for details about using the strptime method.
Try this, I am sure its the shortest and easiest way to go
from dateutil.relativedelta import relativedelta
period = date.today() + relativedelta(weeks=+1)
you can use datetime.strptime to get input from user as date
from datetime import datetime
i = str(raw_input('date'))
try:
dt_start = datetime.strptime(i, '%Y, %m, %d')
except ValueError:
print "Incorrect format"
and then to add 3 weeks (21 days)
dt_start = dt_start + datetime.timedelta(days=21)
There you go