I have a function that removes a file after a certain amount of time. The problem is that it works at later parts of the month, but when I try and remove 7 days from the start of the month it will not substract into the previous month. Does anyone know how to get this to work? The code is below that works out the date and removes the days.
today = datetime.date.today() # Today's date Binary
todaystr = datetime.date.today().isoformat() # Todays date as a string
minus_seven = today.replace(day=today.day-7).isoformat() # Removes 7 days
Thanks for any help.
minus_seven = today - datetime.timedelta(days = 7)
The reason this breaks is that today is a datetime.date; and as the docs say, that means that today.day is:
Between 1 and the number of days in the given month of the given year.
You can see why this works later in the month; but for the first few days of the month you end up with a negative value.
The docs immediately go on to document the correct way to do what you're trying to do:
date2 = date1 - timedelta Computes date2 such that date2 + timedelta == date1.
Related
I was asked to create a program that calculates the number of Sundays inbetween 2 dates! I have been searching numerous articles and documentation but I still have a hard time understanding syntax. (2 months into my coding course with 0 technology and computer experience.)
I am having trouble understanding the logic of how to associate the calendar with the days inside the Dictionary. My current code is as follows :
def difference_between_days():
daysDict = {0 : "Monday",1: "Tuesday",2: "Wedensday",3: "Thursday",4: "Friday",5:
"Saturday",6: "Sunday"}
first_date = date(2021,7,28)
end_date = date(2022,7,28)
difference_between_dates = end_date - first_date
print(f"There are {difference_between_dates.days} days inbetween the two dates!")
d = date.weekday(first_date)
dd = daysDict[d]
print(f"The first date selected is a : {dd}")
difference_between_days()
edit: When using certain functions such as .isoweekday I run into problems printing because it returns me something like this "<built-in method isoweekday of datetime.date object at 0x000001EB956FA0F0>" and I still have not reached classes yet!
Python is not my weapon of choice, but this should do the job.
The idea is to use weekday() to move the start date to the following sunday, and the endate to the previous sunday. Then count the days in between, divide by 7 (weeks) and add 1 because both ends are Sundays.
Don't hesitate to ask if it's not clear, and accept the answer if it it.
HTH
from datetime import datetime, timedelta
def number_of_sundays(from_str, to_str):
# get date objects from the string representations in Ymd format
from_date = datetime.strptime(from_str, "%Y/%m/%d")
to_date = datetime.strptime(to_str, "%Y/%m/%d")
# move start date to the following sunday
from_date = from_date + timedelta(days=6-from_date.weekday())
# move end date to the previous sunday
to_date = to_date + timedelta(days=-to_date.weekday()-1)
# now both dates are sundays so the number is the number of weeks + 1
nb_sundays = 1 + (to_date - from_date).days / 7
return nb_sundays
print(number_of_sundays("2022/08/28", "2022/09/20"))
I would like to know how many days are passed from a x ago to today
I wrote this:
from datetime import datetime
timestamp = 1629195530 # A month ago
before = datetime.fromtimestamp(timestamp)
daysBefore = before.strftime("%d")
now = datetime.now()
today = now.strftime("%d")
print(f"daysBefore {daysBefore} - today {today}")
daysPassed = int(today) - int(daysBefore)
But so it seems, daysBefore is returning the days of the month, I can't get my head around this :(
Exact format with date time hour minute accuracy
from datetime import datetime
timestamp = 1629195530 # A month ago
before = datetime.fromtimestamp(timestamp)
now = datetime.now()
print(now - before))
print(f"daysBefore {daysBefore} - today {today}")
The reason this doesn't work is that it gives the day of the month. For example 17th of July and 17th of August will give a difference of zero days.
Therefore the recommend method is as #abdul Niyas P M says, use the whole date.time format to subtract two dates and afterwards extract the days.
Your issue is due to this: strftime("%d")
You are converting you date to a string and then to an int to make the difference. You can just use the datetime to do this for you:
timestamp = 1629195530 # A month ago
before = datetime.fromtimestamp(timestamp)
now = datetime.now()
print(f"daysBefore {before} - today {now}")
daysPassed = now - before
print(daysPassed.days)
how to get same day last year in python
I tried datetime.datetime.now() - relativedelta(years=1) but this doesn't produce the result I'm looking.
Can anyone help. Thanks
example:
20/08/2020 (Thursday) last year will be 22/08/2019 (Thursday)
The answer from Pranav Hosangadi here is very nice, but please note that not every year has 52 weeks! It may be also 53, if you follow the
ISO8601 week numbering standard.
Number of ISO weeks in a year may be get according to this Stack Overflow thread, resulting in you code:
print(datetime.datetime.now())
2020-08-20 22:57:28.061648
def lastweeknumberoflastyear():
return datetime.date(datetime.datetime.now().year-1, 12, 28).isocalendar()[1]
print(datetime.datetime.now() - datetime.timedelta(weeks=lastweeknumberoflastyear()))
2019-08-22 22:57:28.061785
You want the same day of week one year ago. A year has 52 weeks
print(datetime.datetime.now())
2020-08-20 17:56:56.397626
print(datetime.datetime.now() - datetime.timedelta(weeks=52))
2019-08-22 17:56:56.397626
You can do something like:
now = datetime.datetime.now()
last_year = now.replace(now.year - 1)
Note that this will not account for leap years. If you want to find a date exactly 365 days prior, you would instead do something like:
now = datetime.datetime.now()
last_year = now - datetime.timedelta(days=365)
I'd probably do it like this, as a year is not always 365 days.
from datetime import datetime
x = datetime.now()
last_year = datetime(x.year-1,x.month,x.day,x.hour,x.minute,x.second,x.microsecond)
Let's say you want to look at today's date and then get the same date but last year:
today = datetime.date.today()
previous_year = today.year -1
today_last_year = today.replace(year = previous_year)
I am trying to automate a code. I would like to have the code pull data starting at the beginning of the month to end of the previous day. Currently I am using the following command to get the enddate:
dateEnd = pd.to_datetime('today')
How do tell the code, based on what today is to go back to the beginning of the month? AND, how do I tell the code if its the first of the month to return the previous months data?
For a bonus, once I have the start and end date, how do return find the number of days in the month? I have tried this command, but it does not want to work on a single date.
startTime_date.dt.daysinmonth
This will give you the wanted dates:
import datetime
end = datetime.date.today() - datetime.timedelta(1)
start = end.replace(day=1)
daysInMonth = (datetime.date(start.year, start.month + 1, 1) - datetime.timedelta(1)).day
start
#2018-10-01
end
#2018-10-09
daysInMonth
#31
I need Calculate dates for week in python
I need this
year = 2012
week = 23
(a,b) = func (year,week)
print a
print b
>>>2012-04-06
>>>2012-06-10
Could you help me ?
The date object contains a weekday() method.
This returns 0 for monday 6 for sunday.
(From googling) here is one solution: http://www.protocolostomy.com/2010/07/06/python-date-manipulation/ )
I think this can be made a little less verbose so here's my stab at it:
def week_magic(day):
day_of_week = day.weekday()
to_beginning_of_week = datetime.timedelta(days=day_of_week)
beginning_of_week = day - to_beginning_of_week
to_end_of_week = datetime.timedelta(days=6 - day_of_week)
end_of_week = day + to_end_of_week
return (beginning_of_week, end_of_week)
Little outdated answer, but there is a nice module called isoweek that really gets the trick done. To answer the original question you could do something like:
from isoweek import Week
week = Week(2012, 23)
print(week.monday())
print(week.sunday())
Hope this helps anybody.
I think #Anthony Sottile's answer should be this:
def week_magic(day):
day_of_week = day.weekday()
to_beginning_of_week = datetime.timedelta(days=day_of_week)
beginning_of_week = day - to_beginning_of_week
to_end_of_week = datetime.timedelta(days=6 - day_of_week)
end_of_week = day + to_end_of_week
return (beginning_of_week, end_of_week)
It works!
I think the answer he is looking for is in datetime.isocalendar(datetime)
It returns a 3-tuple containing ISO year, week number, and weekday.
From any particular year (i.e '2015') one can determine the first day of the first week and then from there keep adding days using the timedelta function to find the particular week requested. With this information one can then return the first and last day of that week.