Converting time to epoch (Python) [duplicate]

你离开我真会死。 提交于 2019-12-07 05:21:46

问题


I am using tweepy to get a tweet. I am trying to send this tweet over Slack. Tweepy gives the time in a strange format, and Slack requires the time in epoch.

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

This returns

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

How can I get 2017-01-17 14:36:26 into epoch time?


回答1:


You have to convert the string to time tuple -by appropriate spec, and then time tuple to EPOCH time. In Python it's a little bit awkward

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

The result is 1484656586.0




回答2:


I don't know the type of created but this should work:

from datetime import datetime

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


来源:https://stackoverflow.com/questions/41699998/converting-time-to-epoch-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!