Python字符串到时间戳

时间:2017-01-31 21:40:57

标签: python python-2.7

我正在尝试将这些字符串转换为时间戳:

import 'whatwg-fetch';
import MarkdownIt from 'markdown-it';
import registerPromiseWorker from 'promise-worker/register';

const markdown = new MarkdownIt();

registerPromiseWorker(async url => {
  const response = await fetch(url);
  const text = await response.text();
  return markdown.render(text);
});

我在执行以下代码时得到此输出:

python test.py 

2015-02-15T14:25:54+00:00
2015-02-15T16:59:01+00:00
2015-02-15T18:44:13+00:00
2015-02-15T18:45:24+00:00
2015-02-15T18:52:11+00:00
2015-02-15T18:52:33+00:00
2015-02-15T18:59:00+00:00
2015-02-15T19:06:16+00:00
2015-02-15T19:07:02+00:00

但是当我试图获得时间戳时:

for member in members_dict['members']:
    s = member['timestamp_signup']
    print s

我收到错误:

for member in members_dict['members']:
    s = member['timestamp_signup']
    print s
    print time.mktime(datetime.datetime.strptime(s, "%Y-%m-%dT%H:%M:%S+00:00").timetuple())

我在这里做错了什么?

1 个答案:

答案 0 :(得分:3)

将字符串转换为datetime的代码很好。例如:

>>> from datetime import datetime
>>> my_str = '2015-02-15T14:25:54+00:00'
>>> datetime.strptime(my_str, "%Y-%m-%dT%H:%M:%S+00:00")
datetime.datetime(2015, 2, 15, 14, 25, 54)

您收到的错误是由于您的文件中存在空字符串。我根据您的错误消息了解了它:

ValueError: time data '' does not match format 
#         empty string ^

可能文件末尾(或其他地方)有空行