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.
how to calculate date difference in micropython
Re: how to calculate date difference in micropython
Check time.localtime([secs]) from the docs. Using that you will receive an 8-tuple. Do some calculating for your desired representation.
- pythoncoder
- Posts: 5956
- Joined: Fri Jul 18, 2014 8:01 am
- Location: UK
- Contact:
Re: how to calculate date difference in micropython
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.
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
Index to my micropython libraries.
Index to my micropython libraries.