时间字符串转换为时间戳

遇到一个问题,把形如20150728102148的字符串转换为时间戳。在shell和awk中没有找到解决方案,可是却找到了一个c语言的办法,程序以下:python

#include <time.h>
#include <stdio.h>
#include <string.h>
int main(int argc, char **argv ) { 
    struct tm tm; 
    char buf[255];
    char src[255];
    strptime(argv[1], "%Y%m%d%H%M%S" , &tm);
    memset(buf,0,sizeof(buf));
    strftime(buf, sizeof(buf), "%s", &tm);
    puts(buf);
    return 0;
   }

利用strptime和strftime函数就能够实现转换,strftime是把时间结构体转换为字符串,strptime相反,把字符串转换为时间结构体。shell

编译后执行以下命令:函数

./convert_date_string_to_epoch 20150728102148

convert_date_string_to_epoch 是编译后的可执行文件名。.net

python实现这个功能也比较简单:code

python
>>> str="20150728102148"
>>> format="%Y%m%d%H%M%S"
>>> time.mktime(time.strptime(str, format) )
1438050108.0

不知道是否还有更好的方法。orm

相关文章
相关标签/搜索