2

I'm new to python and am trying to do something that seems trivial: I want to add an if-not-modified header to an http request passing the time, now minus 60 seconds. I'm running into a bunch of difficulty with the now() - 60 seconds part.

I've looked at this How do I convert local time to UTC in Python?, this How can I convert a datetime object to milliseconds since epoch (unix time) in Python?, and many other questions but there has to be a more straightforward way than this sort of approach:

time.strftime("%Y-%m-%d %H:%M:%S", 
              time.gmtime(time.mktime(time.strptime("2008-09-17 14:04:00", 
                                                    "%Y-%m-%d %H:%M:%S"))))

to get the correct time and pass it as an arg to addheaders.

Here's my code so far:

interval = 60 #changes other places 
timestamp = datetime.datetime.now() - datetime.timedelta(seconds=interval)

opener.addheaders("if-modified-since", time.strftime('%a, %d %b %Y %H:%M:%S GMT', time.gmtime(time.mktime(time.strptime(timestamp, "%Y-%m-%d %H:%M:%S")))))

which throws a TypeError: expected string or buffer but all in all, it seems like utter insanity to go through this much munging around to get something as simple as now() + 60 seconds in a UTC string. Can someone with more python ninja-foo please help me see the error of my ways?

Cees Timmerman
  • 17,623
  • 11
  • 91
  • 124
Brad
  • 6,106
  • 4
  • 31
  • 43
  • 2
    `if-modified-since` with now+60 seems strange (will only get files modified in one minute from now). are you sure you don't mean now-60 (modified in the last minute) - or `interval=-60`? – mata Jul 29 '13 at 20:37
  • @mata - yep. got mixed up while writing the post – Brad Jul 30 '13 at 15:20

1 Answers1

3

datetime has a method utcnow which returns the current time in UTC instead of local time, so you can shorten your code to:

from datetime import datetime, timedelta
timestamp = datetime.utcnow() + timedelta(seconds=60)
opener.addheaders("if-modified-since", timestamp.strftime('%a, %d %b %Y %H:%M:%S GMT'))
mata
  • 67,110
  • 10
  • 163
  • 162