1

I would like to know the best approach from the below solutions to calculate the time difference in minutes between the current Linux timestamp with the given epoch value (for example "1512082800" extracted from ETL data):

python - Difference between two unix timestamps

old = datetime.datetime.fromtimestamp(float(epoch_value)) # eg: 1512082800
cur = datetime.datetime.utcnow()
print((cur - old).total_seconds() / 60) # difference between two Unix timestamps in minutes

Date difference in minutes in Python

fmt = '%Y-%m-%d %H:%M:%S'
cur = datetime.datetime.strptime(time.strftime(fmt), fmt)
epoch = datetime.datetime.fromtimestamp(float(1512082800)).strftime(fmt)
old = datetime.datetime.strptime(epoch, fmt)

old = time.mktime(old.timetuple())
cur = time.mktime(cur.timetuple())

# They are now in seconds, subtract and then divide by 60 to get minutes
print int(cur-old) / 60
Ibrahim Quraish
  • 3,889
  • 2
  • 31
  • 39

1 Answers1

1

it is probably best to use time.time() here [docs] - since this gives you seconds since the epoch, you can directly calculate the desired delta in minutes as (time.time() - timestamp)/60.

Timeit comparison vs. getting the current timestamp asdatetime.datetime.utcnow():

import time
from datetime import datetime

%timeit (time.time() - 1512082800) / 60
221 ns ± 10.4 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

%timeit (datetime.utcnow().timestamp() - 1512082800) / 60
848 ns ± 14.1 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
FObersteiner
  • 22,500
  • 8
  • 42
  • 72