how to calculate date difference in micropython

General discussions and questions abound development of code with MicroPython that is not hardware specific.
Target audience: MicroPython Users.
Post Reply
Guru
Posts: 1
Joined: Sun Dec 17, 2017 8:28 pm

how to calculate date difference in micropython

Post by Guru » Sun Dec 17, 2017 8:30 pm

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.

User avatar
kfricke
Posts: 342
Joined: Mon May 05, 2014 9:13 am
Location: Germany

Re: how to calculate date difference in micropython

Post by kfricke » Mon Dec 18, 2017 8:11 am

Check time.localtime([secs]) from the docs. Using that you will receive an 8-tuple. Do some calculating for your desired representation.

User avatar
pythoncoder
Posts: 3241
Joined: Fri Jul 18, 2014 8:01 am
Location: UK
Contact:

Re: how to calculate date difference in micropython

Post by pythoncoder » Tue Dec 19, 2017 8:47 am

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))
Peter Hinch

Post Reply