the number of days between two string-type dates

Question:

i iam trying to fing the number of dates between a given dat and todays date.
given date: 2022-10-10T09:01:38.581210Z

todays date:
i ran this code:

from datetime import datetime
now = datetime.now()
    # dd/mm/YY H:M:S
    dt = now.strftime("%Y-%m-%d" + "T" + "%H:%M:%S" + "Z")

my output for todays date:
2022-10-11T08:29:36Z

i am trying to get the number of days between these two dates. they are both strings and i can not perform simple subtraction. please help

Asked By: Brie Tasi

||

Answers:

you can do it with out convert your datetime to string

(given_date - now).days # will give you number of days between dates

given_date and now are both datetime Object

Answered By: Lior Tabachnik

You should do something like this is better i think, you import module datetime and then we substract the two dates and we get how many days.

from datetime import date
 
def numOfDays(date1, date2):
    return (date2-date1).days
     
# Driver program
date1 = date(2018, 12, 13)
date2 = date(2019, 2, 25)
print(numOfDays(date1, date2), "days")
Answered By: opitimus

It seems you have trouble converting your past date 2022-10-10T09:01:38.581210Z from string to a datetime object, is that right?

You shall set you format right:

from datetime import datetime
past_date = datetime.strptime("2022-10-10T09:01:38.581210Z", "%Y-%m-%dT%H:%M:%S.%fZ")
print(datetime.now() - past_date)

Output:

1 day, 1:41:12.762025

You can return the number of elapsed days as integer with print((datetime.now() - past_date).days)

Answered By: Tranbi

From your data, by applying the correct corresponding format template and setting up the UTC timezone to the method datetime.now, we can convert the strings in datetime format :

from datetime import datetime, timezone

dt_1 = datetime.now(timezone.utc)
dt_2 = datetime.strptime("2022-10-10T09:01:38.581210Z", "%Y-%m-%dT%H:%M:%S.%f%z") 

Then, a substraction with the days attribute allow us to get the expected result :

(dt_1 - dt_2).days
Answered By: tlentali
import datetime
your_date =  '2022-09-01'
i =1
while(True):
  d = today - datetime.timedelta(days=i)
  i = i+1
  if ( str(d) == your_date ):
    break

print(i)
Answered By: Tharindu Kavinda