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
Related
I have a day/month string, I want to convert that string to date object and compare the last day of that month to another date
Example:
For 08/2021 (august, 2021) I want to compare the last day of that month (31-08-2021) to another date (date field),
For 02/2020 I what to compare 29-02-2020 < another_date (date field)
For 02/2021 I what to compare 28-02-2020 < another_date (date field)
You can use calendar.monthrange to find the last day in the month if you don't want to add dateutil.
import calendar
from datetime import datetime
def get_last_day_date(year_month_str):
date = datetime.strptime(year_month_str, "%m/%Y")
last_day = calendar.monthrange(date.year, date.month)[1]
return datetime(date.year, date.month, last_day)
get_last_day_date("08/2020")
# datetime.datetime(2020, 8, 31, 0, 0)
This examples shows you how to convert '02/2020' to a Python datetime and how to get the last day of that month. You can use it to compare the result to another datetime:
import datetime
from dateutil.relativedelta import relativedelta
date = '02/2020'
last_day = datetime.datetime.strptime(date, '%m/%Y') + relativedelta(day=31)
# last_day will be a datetime of the last day of the month which you can use to compare against another datetime
In this example, the result is datetime.datetime(2020, 2, 29, 0, 0) because 2020 was a leap year
b='08/2021'
a=b.split('/')
import calendar
import datetime
z=(str(calendar.monthrange(int(a[1]),int(a[0]))[1])+'-'+b.replace('/','-'))
d=datetime.datetime.strptime(z,'%d-%m-%Y').date()
print(d)
n=datetime.date.today()
print(n)
n<d
Output:
2021-08-31
2021-01-28
True
It can be done by just importing/using datetime library and here you can see how.
By passing string date into method.
import datetime
def convert_string_to_datetime(self, datetime_in_string):
datetime_in_string = str(datetime_in_string)
datetime_format = "%Y-%m-%d %H:%M:%S"
datetime_in_datetime_format = datetime.datetime.strptime(datetime_in_string, datetime_format)
return datetime_in_datetime_format
new_datetime_field = convert_string_to_datetime(datetime_in_string)
By modifying with in single line
import datetime
new_datetime_field = datetime.datetime.strptime(YOUR_DATETIME_IN_STRING, "%Y-%m-%d %H:%M:%S")
After converting into datetime now comparison is possible like.
if new_datetime_field > odoo_datetime_field:
pass
I want to change date format using Python. I don't know How to do that.
I have date format as shown below
2020-10-22 12:14:41.293000+00:00
I want to change above date format into below format:
date(2020, 10, 22)
I want this format because I want to get different between two dates.
with above format I can get difference by using following code,
d0 = date(2017, 8, 18)
d1 = date(2017, 10, 26)
delta = d1 - d0
print(delta.days)
So how to Change date Format as I discussed above.and also let me know if anyone know other way to get difference between these two dates 2020-10-22 12:14:41.293000+00:00 and 2020-10-25 12:14:41.293000+00:00 without changing its formet.I will be thankful if anyone can help me with this issue.
use fromisoformat and date() to get only the date, without the time:
from datetime import datetime
d = datetime.fromisoformat('2020-10-22 12:14:41.293000+00:00').date()
# d
# datetime.date(2020, 10, 22)
To convert a string to a datetime object, we use the datetime module.
from datetime import datetime
def str_to_date(s):
s = s.split()[0] # Separate the str by spaces and get the first item (the date)
s = datetime.strptime(s, "%Y-%m-%d")
return s # You now have a datetime object to do operations on.
If the format is always in the form YYYY-MM-DD ..... then you can strip the first 10 characters of the date and use datetime to convert into datetime object
from datetime import datetime
unformatted_date = "2020-10-22 12:14:41.293000+00:00"
date_obj = datetime.strptime(unformatted_date[0:11], "%Y-%m-%d").date()
print(date_obj)
Change string to datetime format:
from datetime import datetime
date1 = datetime.strptime('2020-10-22 12:14:41.293000+00:00', '%Y-%m-%d %H:%M:%S.%f%z').date()
date2 = datetime.strptime('2020-10-23 12:14:41.293000+00:00', '%Y-%m-%d %H:%M:%S.%f%z').date()
print(date2-date1)
#1 day, 0:00:00
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
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.
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.