5

Is there a simple way to state that

a = '2020-01-01 19:30:33.996628' 
b = '2020-01-01 19:30:34' 

a and b are equal. If the time resolution of a is changed to second, then a could be equal to b. How to implement it with code?

Trenton McKinney
  • 56,955
  • 33
  • 144
  • 158
ComplicatedPhenomenon
  • 4,055
  • 2
  • 18
  • 45

4 Answers4

3

To make it clear, the following options are not the same as rounding, which could have an ambiguous outcome (e.g. Is floating point math broken?).

Set to next second

  • Add the timedelta difference between 1e6 and a.microsecond
from datetime import timedelta, datetime

a = datetime.fromisoformat('2020-01-01 19:30:33.996628')

a = a + timedelta(microseconds=(1e6 - a.microsecond))

print(a)

>>> datetime.datetime(2020, 1, 1, 19, 30, 34)

print(a.strftime('%Y-%m-%d %H:%M:%S'))

>>> 2020-01-01 19:30:34

Set to current second

from datetime import datetime

a = datetime.fromisoformat('2020-01-01 19:30:33.996628')

print(a)

>>> datetime.datetime(2020, 1, 1, 19, 30, 33, 996628)

a = a.replace(microsecond=0)

print(a)

>>> datetime.datetime(2020, 1, 1, 19, 30, 33)

Trenton McKinney
  • 56,955
  • 33
  • 144
  • 158
2

if you treat both of them as datetime objects, you can use arithmetic operators on them. For example, you can subtract them and check if the result satisfy a condition (like less then one minute different) as you wise

Roim
  • 2,986
  • 2
  • 10
  • 25
0

An easier way to use rounding for comparison:-

import datetime
from dateutil import parser

a = '2020-01-01 19:30:33.996628' 
b = '2020-01-01 19:30:34' 

a = parser.parse(a)
b = parser.parse(b)

a == b
False

format_str = '%Y-%m-%d %H:%M'

a_rounded = datetime.datetime.strptime(datetime.datetime.strftime(a, format_str), format_str)
b_rounded = datetime.datetime.strptime(datetime.datetime.strftime(b, format_str), format_str)

a_rounded == b_rounded
True

To this you can add flexibility according to your need like I have rounded up to comparison in Minutes. So in your case the format_str would be like this:-

format_str = '%Y-%m-%d %H:%M:%S'
Shashishekhar Hasabnis
  • 1,636
  • 1
  • 15
  • 36
-1

The other answers do not perform rounding to the nearest second which is normally the best solution for this kind of task. The function datetime_round_s() below performs this kind of rounding:

import datetime

def datetime_round_s(date_time: datetime.datetime) -> datetime.datetime:
    return (date_time + datetime.timedelta(microseconds=5e5)).replace(microsecond=0)

a = datetime.datetime.fromisoformat('2020-01-01 19:30:33.996628')
b = datetime.datetime.fromisoformat('2020-01-01 19:30:34')

print(a)
print(datetime_round_s(a))
print(datetime_round_s(a) == b)

otuput:

2020-01-01 19:30:33.996628
2020-01-01 19:30:34
True

Note: If rounding bias could be a problem then the algorithm should be changed. See for example Rounding half to even.