将时间转换为epoch(Python)

2024-05-16 23:03:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我在用tweepy发推特。我试图通过Slack发送这条tweet。Tweepy以一种奇怪的格式给出时间,而Slack则需要纪元中的时间。

for i in tweets:
    created=(i.created_at)
    print(created)
    print(created.strftime('%s'))

这又回来了

2017-01-17 14:36:26

Traceback (most recent call last):
File "C:\Users\Administrator\Desktop\slackbot3\run.py", line 287, in main
print(created.strftime('%s'))
ValueError: Invalid format string

我怎样才能把2017-01-17 14:36:26变成纪元时间?


Tags: infor格式时间slacktweetsattweet
2条回答

必须根据适当的规范将字符串转换为时间元组,然后将时间元组转换为EPOCH time。在Python中有点尴尬

import time
time_tuple = time.strptime('2017-01-17 14:36:26', '%Y-%m-%d %H:%M:%S')
time_epoch = time.mktime(time_tuple)

结果是1484656586.0

我不知道created的类型,但这应该有效:

from datetime import datetime

print(datetime.strptime(str(created), '%Y-%m-%d %H:%M:%S').strftime('%s'))

相关问题 更多 >