pep 1
pep 1

Reputation: 119

How to get current GMT time in this very format "Sun, 22 Sep 2019 09:18:13 GMT" in python

Even tho it's not used anymore in favor of UTC, the endpoint i am trying to query requires an hmac signature with a date header in this format : "Sun, 22 Sep 2019 09:18:13 GMT"

This deprecated method new Date().toGMTString(); makes the js sdk works, i need an equivalent in python.

time.strftime("%a, %d %b %Y %I:%M:%S %Z", time.gmtime()) returns the full name (i.e. CENTRAL EUROPE TIME) while time.strftime("%a, %d %b %Y %I:%M:%S %z", time.gmtime()) returns "Sun, 22 Sep 2019 09:18:13 +0100".

The closest i got istime.strftime("%a, %d %b %Y %I:%M:%S GMT", time.gmtime()) which in theory print the right string, but i keep getting this error anyway: "{\"message\":\"HMAC signature cannot be verified, a valid date or x-date header is required for HMAC Authentication\"}"

Upvotes: 0

Views: 2272

Answers (2)

Hermueller
Hermueller

Reputation: 195

Have a look here: https://www.programiz.com/python-programming/datetime/strftime

Be sure that you use %Z and not %z.

from datetime import datetime
import time

now = datetime.now() # current date and time

date_time = time.strftime("%a, %d %b %Y %H:%M:%S %Z", time.gmtime())
# output: date and time: Sun, 22 Sep 2019 10:01:53 GMT
print("date and time in GMT:",date_time)

# output: Local: Sun, 22 Sep 2019 10:01:53 AM UTC
print("Local: " + time.strftime("%a, %d %b %Y %I:%M:%S %p %Z\n")) 

Upvotes: 0

Matej Novosad
Matej Novosad

Reputation: 320

import datetime

print(datetime.datetime.now(datetime.timezone.utc).strftime('%a, %d %b %Y %H:%M:%S GMT'))

This works for me :) Source of the formattings

Upvotes: 1

Related Questions