6

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?

Bellerofont
  • 1,081
  • 18
  • 17
  • 16
user2607110
  • 127
  • 1
  • 10
  • 1
    I think, its a dublicate to this question: http://stackoverflow.com/questions/9637838/convert-string-date-to-timestamp-in-python – DiKorsch Jan 17 '17 at 14:49
  • If `created_at` is a `datetime` object, there are other questions that solve your problem: https://stackoverflow.com/questions/6999726/how-can-i-convert-a-datetime-object-to-milliseconds-since-epoch-unix-time-in-p – jdehesa Jan 17 '17 at 14:52
  • @jdehesa Does not look like _datetime_ object - looks like string – volcano Jan 17 '17 at 14:54
  • 1
    @volcano I don't think it's a string, because the object has a `strftime` method - but it does not seem to be a datetime either, because `'%s'` should be a valid format string. Maybe seeing the result of `print(type(created))` could help. – jdehesa Jan 17 '17 at 14:56
  • BTW, are you sure it's Python 2.7? You use _print_ function... – volcano Jan 17 '17 at 15:03
  • @volcano: They used parentheses, but since there was only one "argument", it would work equivalently with the `print` statement or `print` function. – ShadowRanger Mar 19 '19 at 05:33

2 Answers2

7

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

volcano
  • 3,578
  • 21
  • 28
1

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'))
yslee
  • 236
  • 1
  • 12