Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python datetime get only days from datetime object

I am making a website and I want to compare the dates but then when I do that it gives me an extra 0:00:00 which I don't want this is my code:

% if (datetime.datetime.strptime(row['due_date'], "%Y-%m-%d") - cur_date).days <= 0:
      <kbd style="background-color: #a52c2c;">{{datetime.datetime.strptime(row['due_date'], "%Y-%m-%d").date() - cur_date.date()}}</kbd>

% elif (datetime.datetime.strptime(row['due_date'], "%Y-%m-%d") - cur_date).days <= 2:
      <kbd style="background-color: #cc781e;">{{datetime.datetime.strptime(row['due_date'], "%Y-%m-%d").date() - cur_date.date()}}</kbd>

% else:
      <kbd>{{datetime.datetime.strptime(row['due_date'], "%Y-%m-%d").date() - cur_date.date()}}</kbd>
% end

I know it is messy but it works and it returns this: 3 days, 0:00:00 but I don't want the extra minutes etc. I know this might already be asked but I haven't seen anything

like image 895
tygzy Avatar asked Jan 20 '26 22:01

tygzy


2 Answers

This is a nice example for date comparison.

import datetime


str_date = "2019-03-18"

print(datetime.datetime.today().date())

object_date = datetime.datetime.strptime(str_date, '%Y-%m-%d')
if datetime.datetime.today().date() >= object_date.date():
    print(True)
else:
    print(False)

print((object_date.date() - datetime.datetime.today().date()).days)
like image 110
Mehran Jalili Avatar answered Jan 22 '26 11:01

Mehran Jalili


from datetime import date

CurrentDay = date.today().day
print(CurrentDay)

CurrentDay is what you want. It just prints the day.

like image 32
HGalloway Avatar answered Jan 22 '26 10:01

HGalloway



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!