How to compare dates only (and not the time) in python - 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.

Related

How to compare only day, month, and year using timestamp?

How do we can compare 2 dates if they have same date irrespective of timestamp?
For example:
date1 = 1508651293229
date2 = 1508651293220
date1 = datetime.fromtimestamp(int(date1) / 1e3)
date2 = datetime.fromtimestamp(int(date2) / 1e3)
if(date1 == date2):
print(True)
but this checks for entire day stamp including time and I only want to check for day, month, and year.
I tried for some documentation but couldn't find much relevant.
datetime.datetime instances have a date method that returns a datetime.date object, ignoring the time of the original value.
if date1.date() == date2.date():
You can also create the datetime.date instances directly if you don't care about the time, as datetime.date.fromtimestamp also exists.
date1 = datetime.date.fromtimestamp(date1 // 1000)
Try:
if date1.date() == date2.date():
print('True')
# and indeed, they are:
True
datetime.date() returns a date object with the same year, month, and day
In your case, you should use:
if(date1.date() == date2.date()):
print(True)
You can also shorten this by simply doing
print(date1.date() == date2.date())

How to compare today's date and date stored in a string (without time)?

With python, How can I check if a date stored in a string has already passed?
My current code:
from datetime import date, datetime
date1 = date.today()
data2_str = '2018-06-25'
data2_obj = datetime.strptime(data2_str, '%Y-%m-%d')
print(date1<=data2_obj)
The code above gives me the following error:
TypeError: can't compare datetime.datetime to datetime.date
Note that I would not want to work with any time - just the date (this case the treated in 32287708)
Use the .date() method to get the date component like this:
from datetime import date, datetime
date1 = date.today()
date2_str = '2018-06-25'
date2 = datetime.strptime(date2_str, '%Y-%m-%d').date()
print(date1<=date2)
Output:
False

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

What is the quickest way to increment date string YYYY-MM-DD in Python?

In Pandas, I am using dates with string format YYYY-MM-DD
What is the quickest way to increment the date with the result in YYYY-MM-DD format?
d1 = '2018-02-10'
I want to increment it by 1 and get the result back as a string:
d1_inc = '2018-02-11'
Pure Python
You can use the datetime module, part of the standard library. There are 3 steps:
Convert string to datetime object via strptime.
Add a day via timedelta.
Convert resulting datetime object back to string via strftime.
Here's a demo:
from datetime import datetime, timedelta
x = '2017-05-15'
res = (datetime.strptime(x, '%Y-%m-%d') + timedelta(days=1)).strftime('%Y-%m-%d')
print(res)
# 2017-05-16
Pandas
The equivalent steps can be performed using 3rd party Pandas:
x = '2017-05-15'
# choose some combination of below methods
res = (pd.Timestamp(x) + pd.DateOffset(days=1)).strftime('%Y-%m-%d')
res = (pd.to_datetime(x) + pd.Timedelta('1 day')).strftime('%Y-%m-%d')
print(res)
# 2017-05-16
Using pd.to_datetime, pd.TimeDelta and strftime:
fmt = '%Y-%m-%d'
(pd.to_datetime(<your series or column>, format=fmt) + pd.Timedelta('1 days')).dt.strftime(date_format=fmt)
Example
df = pd.DataFrame({'date': ['2017-04-02', '2017-04-23']})
fmt = '%Y-%m-%d'
>>> (pd.to_datetime(df.date, format=fmt) + pd.Timedelta('1 days')).dt.strftime(date_format=fmt)
0 2017-04-03
1 2017-04-24
Name: date, dtype: object
You can perform arithmetic operations with datetime and timedelta objects.
from datetime import datetime, timedelta
d = datetime(year=2018, month=3, day=1)
t = timedelta(days=1)
d + t
# datetime.datetime(2018, 3, 2, 0, 0)
d + t + t
# datetime.datetime(2018, 3, 3, 0, 0)
for i in range(30):
d += 1
print(d)
# datetime.datetime(2018, 3, 31, 0, 0)
You mean like this
date = datetime.date(2015,5,15)
date += datetime.timedelta(days=1)
It depends on what you mean by quickest. I'm assuming you mean the quickest way to program this, not the shortest program execution time (which might be relevant when you're doing lots of these).
from datetime import datetime, timedelta
original_date = '2018-5-15'
print('The original date is {}, the date one day later is: {}'.
format(original_date, (datetime.strptime(original_date, '%Y-%m-%d') +
timedelta(days=1)).strftime('%Y-%m-%d')
Step by step version:
Create a datetime object from the string, note the string that shows python the formatting (see the documentation for more information)
dt = datetime.strptime(original_date, '%Y-%m-%d')
Add a day
dt += timedelta(days=1)
Reformat it back to the requested string
print(dt.strftime('%Y-%m-%d'))
That's all!

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

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)

Categories

Resources