python get same day last year - python

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)

Related

Python: Comparing two dates

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)

Date differences in Python in Years and Days (No Months)

I have two dates: 2005/04/10 and 2018/02/11.
The following code calculates the difference in terms of years, months and days:
from datetime import datetime
from dateutil.relativedelta import relativedelta
start_date = datetime(2005,4,10)
end_date = datetime(2018,2,11)
difference = relativedelta(end_date, start_date)
print(difference.years)
print(difference.months)
print(difference.days)
The output is:
12
10
1
12 years, 10 months and 1 day. The problem is that I am not interested in months I only want it in years and days. In my example, it should be 12 years and 306 days. I know that a good approximation is 10 months*30=300 days but the result is 301, not 306. I want to calculate precisely the days taking into account leap months and the difference in a number of days for each month. Is there any built-in method in Python to do that?
Look I already did my research on StackOverflow to find an answer but all the one related to my question do not answer to my problem.
After the code you already wrote, do this:
mid_date = datetime(start_date.year + difference.years, start_date.month, start_date.day)
print((end_date - mid_date).days)
That gives 307 for your example input.
The idea is to offset the original start_date by difference.years to avoid double-counting that portion of the difference.
Thanks to John's comment I wrote this code that I think satisfies my request:
from datetime import datetime
from dateutil.relativedelta import relativedelta
start_date = datetime(2005,4,10)
end_date = datetime(2018,2,11)
difference = relativedelta(end_date, start_date)
remaining_days = 0
if start_date != datetime(start_date.year, 1, 1):
end_first_year = datetime(start_date.year, 12, 31)
remaining_days += (end_first_year - start_date).days
if end_date != datetime(start_date.year, 1, 1):
begin_last_year = datetime(end_date.year, 1, 1)
remaining_days += (end_date - begin_last_year).days
print(difference.years)
print(remaining_days)
This gives exactly 306 remaining days.
Can anyone suggest a less verbose snippet of code?

Howto calculate first date of week and last date for week in python

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.

Django/Python - Check a date is in current week

I would like to do something like this:
entries = Entry.objects.filter(created_at__in = current_week())
How to make it for good performance. Thanks!
Edit: I still have no idea for current_week() function.
Use __range. You'll need to actually calculate the beginning and end of the week first:
import datetime
date = datetime.date.today()
start_week = date - datetime.timedelta(date.weekday())
end_week = start_week + datetime.timedelta(7)
entries = Entry.objects.filter(created_at__range=[start_week, end_week])
Since Django 1.11, we you can use week Field lookup:
Entry.objects.filter(created_at__week=current_week)
It will give you the week from monday to sunday, according to ISO-8601.
To query for the current week:
from datetime import date
current_week = date.today().isocalendar()[1]
isocalendar() will return a tuple with 3 items: (ISO year, ISO week number, ISO weekday).
Yep, this question is at 2 years ago. Today with more experiences, I recommend using arrow with less pain in handling date time.
Checkout: https://github.com/crsmithdev/arrow

Datetime problem at start of month in Python

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.

Categories

Resources