Converting time to epoch (Python)

user2607110 picture user2607110 · Jan 17, 2017 · Viewed 8.7k times · Source

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?

Answer

volcano picture volcano · Jan 17, 2017

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