Search code examples
pythonpython-3.xdatetimepython-datetimepython-dateutil

How to compare only day, month, and year using timestamp?


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.


Solution

  • 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)