AttributeError: 'datetime.timedelta' object has no attribute 'year' - python

d1 = datetime.strptime(self.current_date, "%Y-%m-%d")
d2 = datetime.strptime(self.dob, "%Y-%m-%d")
current_age = (d1 - d2).year
Running this code give the following error:
AttributeError: 'datetime.timedelta' object has no attribute 'year'

As per the docs (https://docs.python.org/3/library/datetime.html), a timedelta counts days, not years. So try something like (d1 - d2).days / 365.25.

Calculating the difference between 2 dates returns a timedelta (datetime.timedelta) such as (d1 - d2) in your sample code ("A timedelta object represents a duration, the difference between two dates or times."). Available from this are .days, .seconds and .microseconds (only). A timedelta isn't anchored to particular years so it doesn't provide .years since the number of leap years can only be accurately counted once a start date is known (timedelta doesn't have this information). Using the Python REPL,
>>> import datetime
>>> datetime.date(2021,1,1) - datetime.date(2020,1,1)
datetime.timedelta(days=366)
>>> datetime.date(2022,1,1) - datetime.date(2021,1,1)
datetime.timedelta(days=365)
For an exact answer take the original dates' year values and then use their month and day values to work out whether the subject's birthday has occurred this year or not. Adapting your sample code and omitting reference to the class you're clearly using (you don't provide the code for that so it's confusing to include it),
from datetime import date
d1 = date.today()
d2 = date(2000, 1, 1) # Example date
current_age = d1.year - d2.year
if (d1.month, d1.day) < (d2.month, d2.day):
current_age = current_age - 1 # Not had birthday yet
print(current_age)
Alternatively use the dateutil module's relativedelta which is aware of years. For example,
from datetime import date
from dateutil.relativedelta import relativedelta
d1 = date.today()
d2 = date(2000, 1, 1) # Example date
current_age = relativedelta(d1, d2).years
print(current_age)

Related

Compare current date with future date in Python

I am trying to compare the current date in the following format (ddmmyyyy) to a future date in the following format (ddmmyyyy)
I put them in that format so i can easily compare them as integers. However, it keeps failing the if then test.
from datetime import datetime, timedelta
StartDay=datetime.today() # Get current date in this format 2020-04-28 19:59:16.901897
EndDay=StartDay+timedelta(60) # I want to be able to add 60 days to StartDay
print(EndDay.strftime('%d%m%Y')) # Print EndDay as an integer 27062020
EndDay=EndDay.strftime('%d%m%Y') # Convert EndDay to make it look like an integer
StartDay=datetime.today().strftime('%d%m%Y') # Convert the StartDay to make it look like an integer
if int(StartDay)>int(EndDay):
print('Game Over!')
else:
pass
What I want to achieve is the an integer value for a date, such that the future date will always be greater than past/current date if that makes sense.
you can directly compare datetime objects, no need for a detour here:
from datetime import datetime
t0, t1 = datetime(2020,1,1), datetime(2020,1,2)
t0>t1
Out[6]: False
t0<t1
Out[7]: True
t1-t0
Out[8]: datetime.timedelta(days=1)
datetime.datetime might be easily converted into datetime.date and then compared consider following example:
from datetime import datetime, timedelta
StartDay = datetime.today()
EndDay = StartDay + timedelta(60)
StartDate = StartDay.date() # datetime.date(2020, 4, 28)
EndDate = EndDay.date() # datetime.date(2020, 6, 27)
print(StartDate < EndDate) # True
Note that you might also compare datetime.datetime directly with datetime.datetime but this take in account also units smaller than days, so if you have two datetime.datetimes say d1 and d2 with same year-month-day but different hours, then result of d1 < d2 might be different from d1.date() < d2.date()
Keep startdate and enddate as 'datetime' and do the following:
from datetime import datetime, timedelta
StartDay=datetime.today()
EndDay=StartDay+timedelta(60)
delta = (StartDay - EndDay).days
if delta > 0:
print('Game Over!')
else:
print('Something else')
This should do the trick

Subtract a year from given date (not current time) in python

I have a file in which date field in YYYYMMDD format. I need to pick that date and product to join with another file by subtracting 12 months to get other information.
File1
20180131,Apple
20180228,Orange
20180331,Grapes
File2
20170131,Apple,45
20170131,Orange,20
20170228,Orange,35
20170331,Apple,25
Output
20180131,Apple,45
20180228,Orange,35
20180331,Grapes,null
How to subtract 12 months or 1 year from given date(yyyymmdd) and get the answer in the same format.
You can use strptime from the standard library to parse the date, but unfortunately there is no calendar support in the standard library so you have to use the dateutil library to subtract the year.
import datetime
from dateutil.relativedelta import relativedelta
d = datetime.datetime.strptime('20180131', '%Y%m%d').date()
print((d - relativedelta(years=1)).strftime('%Y%m%d'))
This will print 20170131.
Note that if the input is e.g. 20160229, this will print out 20150228. I'm not sure exactly what the semantics of relativedelta are so be sure to read the docs if this is important to you.
Why not timedelta?
The datetime.timedelta is not appropriate and does not work correctly. A timedelta represents a duration in time, or it represents a number of days, but counter-intuitively, a year is not a duration but instead a calendrical concept. A year is either 365 or 366 days, depending on which year.
It becomes pretty obvious that timedelta will not work once you find the correct test cases:
In [1]: from datetime import date, timedelta
In [2]: date(2018, 1, 1) - timedelta(365)
Out[2]: datetime.date(2017, 1, 1)
In [3]: date(2017, 1, 1) - timedelta(365)
Out[3]: datetime.date(2016, 1, 2)

How to use ftplib in Python to change directories when directory name matches a date [duplicate]

I need to find "yesterday's" date in this format MMDDYY in Python.
So for instance, today's date would be represented like this:
111009
I can easily do this for today but I have trouble doing it automatically for "yesterday".
Use datetime.timedelta()
>>> from datetime import date, timedelta
>>> yesterday = date.today() - timedelta(days=1)
>>> yesterday.strftime('%m%d%y')
'110909'
from datetime import datetime, timedelta
yesterday = datetime.now() - timedelta(days=1)
yesterday.strftime('%m%d%y')
This should do what you want:
import datetime
yesterday = datetime.datetime.now() - datetime.timedelta(days = 1)
print yesterday.strftime("%m%d%y")
all answers are correct, but I want to mention that time delta accepts negative arguments.
>>> from datetime import date, timedelta
>>> yesterday = date.today() + timedelta(days=-1)
>>> print(yesterday.strftime('%m%d%y')) #for python2 remove parentheses
Could I just make this somewhat more international and format the date according to the international standard and not in the weird month-day-year, that is common in the US?
from datetime import datetime, timedelta
yesterday = datetime.now() - timedelta(days=1)
yesterday.strftime('%Y-%m-%d')
To expand on the answer given by Chris
if you want to store the date in a variable in a specific format, this is the shortest and most effective way as far as I know
>>> from datetime import date, timedelta
>>> yesterday = (date.today() - timedelta(days=1)).strftime('%m%d%y')
>>> yesterday
'020817'
If you want it as an integer (which can be useful)
>>> yesterday = int((date.today() - timedelta(days=1)).strftime('%m%d%y'))
>>> yesterday
20817

Python count start date + days

I am making a program where I input start date to dataStart(example 21.10.2000) and then input int days dateEnd and I convert it to another date (example 3000 = 0008-02-20)... Now I need to count these dates together, but I didn't managed myself how to do that. Here is my code.
from datetime import date
start=str(input("type start date (DD.MM.YYYY)"))
end=int(input("how many days from it?"))
dataStart=start.split(".")
days=int(dataStart[0])
months=int(dataStart[1])
years=int(dataStart[2])
endYears=0
endMonths=0
endDays=0
dateStart = date(years, months, days)
while end>=365:
end-=365
endYears+=1
else:
while end>=30:
end-=30
endMonths+=1
else:
while end>=1:
end-=1
endDays+=1
dateEnd = date(endYears, endMonths, endDays)
For adding days into date, you need to user datetime.timedelta
start=str(input("type start date (DD.MM.YYYY)"))
end=int(input("how many days from it?"))
date = datetime.strptime(start, "%d.%m.%Y")
modified_date = date + timedelta(days=end)
print(datetime.strftime(modified_date, "%d.%m.%Y"))
You may use datetime.timedelta to add certain units of time to your datetime object.
See the answers here for code snippets: Adding 5 days to a date in Python
Alternatively, you may wish to use the third-party dateutil library if you need support for time additions in units larger than weeks. For example:
>>> from datetime import datetime
>>> from dateutil import relativedelta
>>> one_month_later = datetime(2017, 5, 1) + relativedelta.relativedelta(months=1)
>>> one_month_later
>>> datetime.datetime(2017, 6, 1, 0, 0)
It will be easier to convert to datetime using datetime.datetime.strptime and for the part about adding days just use datetime.timedelta.
Below is a small snippet on how to use it:
import datetime
start = "21.10.2000"
end = 8
dateStart = datetime.datetime.strptime(start, "%d.%m.%Y")
dateEnd = dateStart + datetime.timedelta(days=end)
dateEnd.date() # to get the date format of the endDate
If you have any doubts please look at the documentation python3/python2.

How to compare dates only (and not the time) in python

I have 2 datetime objects. One only has the date and the other one has date & time. I want to compare the dates only (and not the time).
This is what I have:
d2=datetime.date(d1.year,d1.month,d1.day)
print d2 == d1.date
It prints out false. Any idea why?
Thank you!
d1.date() == d2.date()
From the Python doc:
datetime.date() Return date object with same year, month and day.
Cast your datetime object into a date object first. Once they are of the same type, the comparison will make sense.
if d2.date() == d1.date():
print "same date"
else:
print "different date"
For your case above:-
In [29]: d2
Out[29]: datetime.date(2012, 1, 19)
In [30]: d1
Out[30]: datetime.datetime(2012, 1, 19, 0, 0)
So,
In [31]: print d2 == d1.date()
True
All you needed for your case was to make sure you are executing the date method with the brackets ().
For those who wants to compare specific date with today date.
import datetime
# Set specific date
date = '2020-11-21'
# Cast specific date to Date Python Object
date = datetime.datetime.strptime(date, '%Y-%m-%d').date()
# Get today date with Date Python Object
today = datetime.date.today()
# Compare the date
isYesterday = date < today
isToday = date == today
isTomorrow = date > today
>>> datetime.date.today() == datetime.datetime.today().date()
True
For more info
TL&DR:
The DateTime Object has a built in function called date(). You can use this to get the date only of the datetime object.
Example:
current_time_dt_object = datetime.datetime.now()
current_time_only_date = current_time_dt_object.date()
You can now use this current_time_only_date as do any equality operation you want.

Categories

Resources