Page 1 of 1
how to calculate date difference in micropython
Posted: Sun Dec 17, 2017 8:30 pm
by Guru
Hi
I have 2 dates and i wish to calculate the difference between the dates, with the result being shown in days. could anyone show me the way, using utime.
thanks.
Re: how to calculate date difference in micropython
Posted: Mon Dec 18, 2017 8:11 am
by kfricke
Check time.localtime([secs]) from the docs. Using that you will receive an 8-tuple. Do some calculating for your desired representation.
Re: how to calculate date difference in micropython
Posted: Tue Dec 19, 2017 8:47 am
by pythoncoder
A calculation which would be fairly involved given the different lengths of months and the effect of leap years.
I would use
utime.mktime() and integer division to do this.
utime.mktime() converts a date tuple to a number of seconds since the epoch.
Code: Select all
import utime
def days_between(d1, d2):
d1 += (1, 0, 0, 0, 0) # ensure a time past midnight
d2 += (1, 0, 0, 0, 0)
return utime.mktime(d1) // (24*3600) - utime.mktime(d2) // (24*3600)
date1 = (2017, 12, 25)
date2 = (2017, 12, 4)
print(days_between(date1, date2))