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())
Related
My code is the following:
date = datetime.datetime.now()- datetime.datetime.now()
print date
h, m , s = str(date).split(':')
When I print h the result is:
-1 day, 23
How do I get only the hour (the 23) from the substract using datetime?
Thanks.
If you subtract the current date from a past date, you would get a negative timedelta value.
You can get the seconds with td.seconds and corresponding hour value via just dividing by 3600.
from datetime import datetime
import time
date1 = datetime.now()
time.sleep(3)
date2 = datetime.now()
# timedelta object
td = date2 - date1
print(td.days, td.seconds // 3600, td.seconds)
# 0 0 3
You're not too far off but you should just ask your question as opposed to a question with a "real scenario" later as those are often two very different questions. That way you get an answer to your actual question.
All that said, rather than going through a lot of hoop-jumping with splitting the datetime object, assigning it to a variable which you then later use look for what you need in, it's better to just know what DateTime can do since that can be such a common part of your coding. You would also do well to look at timedelta (which is part of datetime) and if you use pandas, timestamp.
from datetime import datetime
date = datetime.now()
print(date)
print(date.hour)
I can get you the hour of datetime.datetime.now()
You could try indexing a list of a string of datetime.datetime.now():
print(list(str(datetime.datetime.now()))[11] + list(str(datetime.datetime.now()))[12])
Output (in my case when tested):
09
Hope I am of help!
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
I am trying to find a way to check if item_date contain today's date. But even I hard code it, print True never happen. Anyone know how to solve this?
for item_date in buy_crossing_dates:
print item_date
print type(item_date)
if item_date == '2015-03-25 00:00:00':
print 'True'
result:
2015-03-25 00:00:00
<class 'pandas.tslib.Timestamp'>
Two options for checking for today's date in a pandas Series of Timestamps ...
import pandas as pd
# option 1 - compare using python datetime.date objects
dates = pd.Series(pd.date_range('2015-01-01', '2016-12-31')) # Timestamps
python_dates = pd.Series([x.date() for x in dates]) # datetime.date
today = pd.Timestamp('now').date() # datetime.date
print(python_dates[python_dates == today])
# option 2 - compare pandas.Timestamp objects using Series.dt accessor
dates = pd.Series(pd.date_range('2015-01-01', '2016-12-31')) # Timestamps
today = pd.Timestamp('now') # Timestamp
print(dates[(dates.dt.year == today.year) &
(dates.dt.month == today.month) &
(dates.dt.day == today.day)])
Note: option one uses a list comprehension to convert a pandas Series of Timestamps to a Series of datetime.date objects (using the pandas.Timestamp.date() method).
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.
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.