前言

10位时间戳:精确到秒
13位时间戳:精确到毫秒

项目需求,翻译python实现的文件,需要将datetime.fromtimestamp以C++方式实现类似功能,即将13位时间戳timestamp(精确到毫秒)转换为标准时间格式(YY-MM-DD hh:mm:ss),后面发现只需要10位时间戳(精确到秒)即可满足需求,故实现如下函数示例:

编译环境

系统环境:

patten@patten-hp:~$ sudo lsb_release -a
No LSB modules are available.
Distributor ID:	Ubuntu
Description:	Ubuntu 16.04.6 LTS
Release:	16.04
Codename:	xenial
patten@patten-hp:~$

IDE环境:Visual Studio Code,Version: 1.38.1

时间戳转标准时间

代码实现:

如下:

// timestamp.cpp

#include <stdio.h>
#include <time.h>
#include <iostream>
#include <string>

using namespace std;

typedef struct times {
  int Year;
  int Mon;
  int Day;
  int Hour;
  int Min;
  int Second;
} Times;

Times stamp_to_standard(int stampTime) {
  time_t tick = (time_t)stampTime;
  struct tm tm;
  char s[100];
  Times standard;

  // tick = time(NULL);
  tm = *localtime(&tick);
  strftime(s, sizeof(s), "%Y-%m-%d %H:%M:%S", &tm);
  printf("%d: %s\n", (int)tick, s);

  standard.Year = atoi(s);
  standard.Mon = atoi(s + 5);
  standard.Day = atoi(s + 8);
  standard.Hour = atoi(s + 11);
  standard.Min = atoi(s + 14);
  standard.Second = atoi(s + 17);
  return standard;
}

int main(int argc, const char *argv[]) {
  long timeStamp = 1549133300623;  // 13位时间戳,精确到毫秒

  stamp_to_standard(timeStamp / 1000);
  return 0;
}

编译运行结果

结果如下:

patten@patten-hp:~/workspace/xjCollide$ g++ timestamp.cpp  -std=c++11
patten@patten-hp:~/workspace/xjCollide$ ./a.out 
1549133300: 2019-02-03 02:48:20
patten@patten-hp:~/workspace/xjCollide$

标准时间转时间戳

代码实现:

如下:

#include <string.h>
#include <iostream>
using namespace std;

long standard_to_stamp(char *str_time) {
  struct tm stm;
  int iY, iM, iD, iH, iMin, iS;
  memset(&stm, 0, sizeof(stm));
  iY = atoi(str_time);
  iM = atoi(str_time + 5);
  iD = atoi(str_time + 8);
  iH = atoi(str_time + 11);
  iMin = atoi(str_time + 14);
  iS = atoi(str_time + 17);
  stm.tm_year = iY - 1900;
  stm.tm_mon = iM - 1;
  stm.tm_mday = iD;
  stm.tm_hour = iH;
  stm.tm_min = iMin;
  stm.tm_sec = iS;
  printf("%d-%0d-%0d %0d:%0d:%0d\n", iY, iM, iD, iH, iMin, iS);

  return (long)mktime(&stm);
}

int main() {
  char arr[20] = "2019-10-21 16:02:30";
  char *a = arr;
  std::cout << "timeStamp: " << standard_to_stamp(arr) << std::endl;

  return 0;
}

编译运行结果

结果如下:

patten@patten-hp:~/workspace/others/cpp/demo$ g++ -g -std=c++11 main.cpp 
patten@patten-hp:~/workspace/others/cpp/demo$ ./a.out 
2019-10-21 16:2:30
timeStamp: 1571644950
patten@patten-hp:~/workspace/others/cpp/demo$

代码说明

其中的+5, +8, +11, +14, +17等分别表示距离字符数组头部的距离。

相关文章

致谢

此去经年.COMc,c++中时间戳与标准时间间的相互转换