Home > Enterprise >  C timedelta with strftime?
C timedelta with strftime?

Time:10-27

I want to do a function to get the current time with a certain format. C is not my main language but im trying to do this:

current_datetime(timezone='-03:00', offset=timedelta(seconds=120))
def current_datetime(fmt='%Y-%m-%dT%H:%M:%S', timezone='Z', offset=None):
    offset = offset or timedelta(0)
    return (datetime.today()   offset).strftime(fmt)   timezone

My best so far searching internet was this, but is missing the offset part:

#include <iostream>
#include <ctime>

std::string current_datetime(std::string timezone="Z", int offset=1)
{
  std::time_t t = std::time(nullptr);
  char mbstr[50];
  std::strftime(mbstr, sizeof(mbstr), "%Y-%m-%dT%H:%M:%S", std::localtime(&t));
  std::string formated_date(mbstr);
  formated_date  = std::string(timezone);
  return formated_date;
}

int main() 
{
    std::cout << current_datetime() << std::endl; //2021-10-26T21:34:48Z
    std::cout << current_datetime("-05:00") << std::endl; //2021-10-26T21:34:48-05:00
    return 0;
}

The idea is to get a string that is a "start date" and one as "end date" that is X seconds in the future. Im stuck with the offset/delta part

CodePudding user response:

Just add the offset to the seconds since epoch.

std::time_t t = std::time(nullptr)   offset;

You would also make offset of type std::time_t, as it represents a distance in time in seconds.

  • Related