0

Converting YYYY/MM/DD HH:MM:SS to epoch time.
Moderators: adafruit_support_bill, adafruit

Please be positive and constructive with your questions and comments.

Converting YYYY/MM/DD HH:MM:SS to epoch time.

by foodini on Sat Oct 10, 2020 7:02 pm

I'm using a couple different Adafruit breakouts - the GPS, of course, and the Micro-SD Breakout Board+. Unfortunately, the interface for the SD expects timestamps to be supplied in epoch time. The GPS gives me date/time and no way to convert from one to the other. (I'm actually surprised that epoch time isn't something a GPS module is aware of and capable of communicating via NMEA.

I recognize that any solution that converts from one to the other is necessarily unreliable because you never know when more leap seconds will be added, but I was hoping to pick a few people's brains for their favorite mechanism for getting an epoch time from a datetime. I'm okay with it slowly drifting by a few seconds every decade. =] Most likely, I'll just grab the epoch time for January 1, 2020 and do some ad hoc math to get the answer, but I'd rather see the capability in the Adafruit_GPS library. (This is the third project I've used this hardware for, and each time have had to work around epoch time issues. I can't circumvent it this time, though.)

Thanks...
foodini
 
Posts: 19
Joined: Wed Aug 08, 2012 2:08 am

Re: Converting YYYY/MM/DD HH:MM:SS to epoch time.

by adafruit_support_bill on Sat Oct 10, 2020 7:50 pm

Arduinos are generally resource constrained systems. So libraries tend to stick to the essentials. If you pull in the RTCLib, it has a DateTime class that can handle the conversion.
https://github.com/adafruit/RTClib

adafruit_support_bill
 
Posts: 81542
Joined: Sat Feb 07, 2009 10:11 am

Re: Converting YYYY/MM/DD HH:MM:SS to epoch time.

by foodini on Sun Oct 18, 2020 4:10 am

The reason I needed epoch time is because I have to call settimeofday() on an ESP32 to make SD card functions apply a timestamp to files properly. Fortunately, having settimeofday() around gives me tm and mktime():

Code: Select all | TOGGLE FULL SIZE
unsigned long epoch_time() {
  struct tm t;
  time_t epoch;

  t.tm_year = GPS->year+100;
  t.tm_mon = GPS->month - 1;
  t.tm_mday = GPS->day;
  t.tm_hour = GPS->hour;
  t.tm_min = GPS->minute;
  t.tm_sec = GPS->seconds;

  epoch = mktime(&t);
  return ((unsigned long)epoch);
}


I like the idea of pulling across RTClib, though. I'll keep that in mind for the next time. (No pun intended.)
foodini
 
Posts: 19
Joined: Wed Aug 08, 2012 2:08 am

Please be positive and constructive with your questions and comments.