0

I would like to know how many days are passed from a x ago to today

I wrote this:

from datetime import datetime

timestamp = 1629195530 # A month ago
before = datetime.fromtimestamp(timestamp)
daysBefore = before.strftime("%d")

now = datetime.now()
today = now.strftime("%d")

print(f"daysBefore {daysBefore} - today {today}")
daysPassed = int(today) - int(daysBefore)

But so it seems, daysBefore is returning the days of the month, I can't get my head around this :(

YakuzaNY
  • 69
  • 8

3 Answers3

1
print(f"daysBefore {daysBefore} - today {today}")

The reason this doesn't work is that it gives the day of the month. For example 17th of July and 17th of August will give a difference of zero days.

Therefore the recommend method is as @abdul Niyas P M says, use the whole date.time format to subtract two dates and afterwards extract the days.

3dSpatialUser
  • 1,388
  • 1
  • 8
  • 14
1

Your issue is due to this: strftime("%d")
You are converting you date to a string and then to an int to make the difference. You can just use the datetime to do this for you:

timestamp = 1629195530 # A month ago
before = datetime.fromtimestamp(timestamp)
now = datetime.now()

print(f"daysBefore {before} - today {now}")
daysPassed = now - before
print(daysPassed.days)
Nimantha
  • 5,793
  • 5
  • 23
  • 56
CyDevos
  • 385
  • 4
  • 10
1

Exact format with date time hour minute accuracy

from datetime import datetime

timestamp = 1629195530 # A month ago
before = datetime.fromtimestamp(timestamp)
now = datetime.now()
print(now - before))
Ehsan Rahi
  • 65
  • 7