Skip to content

Instantly share code, notes, and snippets.

@dybber
Created August 24, 2018 07:07
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dybber/b1f75d1f09cda32fa57f88bc57e3427c to your computer and use it in GitHub Desktop.
Save dybber/b1f75d1f09cda32fa57f88bc57e3427c to your computer and use it in GitHub Desktop.
parse-datetime-micropython.py
import ure
def parseDateTime(datestr):
regex = ("^(19|2[0-9][0-9][0-9])-(0[1-9]|1[012])-(0[1-9]|[12][0-9]|3[01])"
"T(0[0-9]|1[0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9])(.([0-9]*))?"
"((\\+|-)[0-1][0-9]:[0-9][0-9])?$")
match = ure.match(regex, datestr)
if match:
year = int(match.group(1))
month = int(match.group(2))
day = int(match.group(3))
hour = int(match.group(4))
minute = int(match.group(5))
seconds = int(match.group(6))
#match.group(7) - milliseconds
#match.group(8) - timezone
return (year, month, day, hour, minute, seconds)
else:
return None
def dateToUnixTime(tup):
(year, month, day, hours, minutes, seconds) = tup
if month <= 2:
month += 12
year -= 1
# Convert years to days
t = (365 * year) + (year / 4) - (year / 100) + (year / 400)
# Convert months to days
t += (30 * month) + (3 * (month + 1) / 5) + day
# Unix time starts on January 1st, 1970
t -= 719561
# Convert days to seconds
t *= 86400
# Add hours, minutes and seconds
t += (3600 * hours) + (60 * minutes) + seconds
return t
#### EXAMPLES
utime1 = 0
utime2 = 0
datetime = parseDateTime("2018-08-23T22:02:07.249+02:00")
if datetime:
utime1 = dateToUnixTime(datetime)
print(utime1)
datetime = parseDateTime("2018-08-23T22:21:00+02:00")
if datetime:
utime2 = dateToUnixTime(datetime)
print(utime2)
tdiff_seconds = utime2-utime1
print(str(tdiff_seconds) + " seconds")
tdiff_minutes = round((utime2-utime1)/60)
print(str(tdiff_minutes) + " minutes")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment